Laravel 5.2 - 扩展Validator时创建自定义验证消息

时间:2016-06-16 08:04:03

标签: php validation laravel

在我的AppServideProvider的启动方法中,我为西里尔文设置了自定义验证规则。这就是它的样子:

public function boot()
{
    Validator::extend('cyrillic', function ($attribute, $value, $parameters, $validator) {
        return preg_match('/[А-Яа-яЁё]/u', $value);
    });
}

它按预期工作。但是,如果由于拉丁语输入而未通过验证,则会收到错误消息“validation.cyrillic'”。我该如何解决这个问题?如何将自定义消息传递给我的西里尔字母'验证规则?

1 个答案:

答案 0 :(得分:1)

如果要全局定义,则需要编辑验证文件,这些验证文件位于resources/lang/LANG/validation.php LANG,其中resources/lang/en/validation.php是您要定义的语言。

例如,对于英语版本,请打开文件return [ 'accepted' => 'The :attribute must be accepted.', 'active_url' => 'The :attribute is not a valid URL.', // Add yours to somewhere in the first level of the array 'cyrillic' => 'The :attribute is not Cyrillic.' ] 并添加如下信息。

public function messages()
{
    return [
        'cyrillic' => 'The :attribute is not Cyrillic.'
    ];
}

对于本地,您可以在请求中定义它。

names = ["show me 7 wonders of the world","most beautiful places","top 10 places to visit","Population > 1000","Cost greater than 100"]