如何在使用自定义验证器解析器时使用验证名称和属性 [laravel 6]
How to use validation names and attributes while using custom validator resolver [laravel 6]
我使用 Validator::resolver()
添加了自定义验证错误,如下所示:
class Rest extends Validator
{
public function addFailure($attribute, $rule, $parameters = [])
{
$message = $this->getMessage($attribute, $rule);
$message = $this->makeReplacements($message, $attribute, $rule, $parameters);
$customMessage = new MessageBag();
$customMessage->merge(['code' => strtolower($rule.'_rule_error')]);
$customMessage->merge(['message' => $message]);
$this->messages->add($attribute, $customMessage);
}
}
我在 AppServiceProvider
中使用解析器调用它:
Validator::resolver(function($translator, $data, $rules, $messages)
{
return new Rest($translator, $data, $rules, $messages);
});
并且在尝试更改属性名称时它不起作用:
$request->validate(
[
'group_id' => 'required'
], [],
[
'group_id' => 'the lesson group'
]);
我通常在提供商注册时扩展验证器
例如:
Validator::extend('foo', function ($attribute, $value, $parameters, $validator) {
return $value == 'foo';
});
记住你需要 return 是或否。
更多信息:https://laravel.com/docs/6.x/validation#using-extensions
我使用 Validator::resolver()
添加了自定义验证错误,如下所示:
class Rest extends Validator
{
public function addFailure($attribute, $rule, $parameters = [])
{
$message = $this->getMessage($attribute, $rule);
$message = $this->makeReplacements($message, $attribute, $rule, $parameters);
$customMessage = new MessageBag();
$customMessage->merge(['code' => strtolower($rule.'_rule_error')]);
$customMessage->merge(['message' => $message]);
$this->messages->add($attribute, $customMessage);
}
}
我在 AppServiceProvider
中使用解析器调用它:
Validator::resolver(function($translator, $data, $rules, $messages)
{
return new Rest($translator, $data, $rules, $messages);
});
并且在尝试更改属性名称时它不起作用:
$request->validate(
[
'group_id' => 'required'
], [],
[
'group_id' => 'the lesson group'
]);
我通常在提供商注册时扩展验证器
例如:
Validator::extend('foo', function ($attribute, $value, $parameters, $validator) {
return $value == 'foo';
});
记住你需要 return 是或否。
更多信息:https://laravel.com/docs/6.x/validation#using-extensions