Aje*_*shy 10 php laravel laravel-validation
我想创建这个扩展验证.
Validator::extend('my_custom_validation_rule', function ($attribute, $value, $parameters) {
// I guess I should be setting the error message for this here.(Its dynamic)
// We can return true or false here depending upon our need.
}
Run Code Online (Sandbox Code Playgroud)
我会像这样使用这个规则
'my_field' => 'required|my_custom_validation_rule'
,
我想使用一些动态消息来解决" my_custom_validation_rule
" 的错误
我无法从文档中找到有关它的内容.无论如何要做到这一点?
luk*_*ter 27
该extend
方法允许将消息作为第三个参数传递:
Validator::extend('my_custom_validation_rule', function ($attribute, $value, $parameters) {
// ...
}, 'my custom validation rule message');
Run Code Online (Sandbox Code Playgroud)
默认情况下,您只能使用动态变量:attribute
.如果您想添加更多用途Validator::replacer()
:
Validator::replacer('my_custom_validation_rule', function($message, $attribute, $rule, $parameters){
return str_replace(':foo', $parameters[0], $message);
});
Run Code Online (Sandbox Code Playgroud)
小智 8
这与@lukasgeiter的答案基本相同,但是如果您需要在扩展函数内管理动态变量,您可以$validator->addReplacer
直接在扩展内使用。
Validator::extend('my_custom_validation_rule', function ($attribute, $value, $parameters, $validator) {
// Test custom message
$customMessage = request()->get('foo')
? "Foo doesn't exist"
: "Foo exist";
// Replace dynamic variable :custom_message with $customMessage
$validator->addReplacer('my_custom_validation_rule',
function($message, $attribute, $rule, $parameters) use ($customMessage) {
return \str_replace(':custom_message', $customMessage, $message);
}
);
// Test error message. (Make it always fail the validator)
return false;
}, 'My custom validation rule message. :custom_message');
Run Code Online (Sandbox Code Playgroud)
您还可以在验证翻译文件下为您的自定义验证规则定义消息。
/resources/lang/en/validation.php
....
'unique' => 'The :attribute has already been taken.',
'uploaded' => 'The :attribute failed to upload.',
'url' => 'The :attribute format is invalid.',
//place your translation here
'my_custom_validation_rule' => 'The :attribute value fails custom validation.'
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7137 次 |
最近记录: |