2015-05-04 205 views
3

我想创建此扩展验证。Laravel扩展验证自定义消息

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. 
} 

我会用这个规则是这样

'my_field' => 'required|my_custom_validation_rule'

我想用一些动态消息的错误“my_custom_validation_rule

我无法找到的东西有关它的文档。无论如何去做?

+2

再看看:http://laravel.com/docs/5.0/validation#custom-error-messages – lukasgeiter

+0

我想在Validator :: extend中提供消息('my_custom_validation_rule',s closure本身,有可能吗? –

回答

13

extend方法允许通过将消息作为第三个参数:

Validator::extend('my_custom_validation_rule', function ($attribute, $value, $parameters) { 
    // ... 
}, 'my custom validation rule message'); 

在默认情况下,只能使用动态变量,这是:attribute。如果你想添加更多的使用Validator::replacer()

Validator::replacer('my_custom_validation_rule', function($message, $attribute, $rule, $parameters){ 
    return str_replace(':foo', $parameters[0], $message); 
}); 
+0

有没有什么办法可以让这个消息变成动态的呢?我的意思是我的消息根据$ attribute,$ value,$参数 - 我可以像第二个参数一样使用闭包吗? –

+0

查看已更新的答案 – lukasgeiter

0

您也可以定义为待验证的翻译文件自定义的验证规则的消息。

/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.'