Laravel 5 - 如何在验证中添加自定义消息?

时间:2016-09-01 06:01:30

标签: php laravel-5

我试图找出如何在Laravel 5中快速添加每个字段的错误消息。这是我得到的:

$validator = Validator::make($this->req->all(), [
'email_add' => 'required|email|max:100',
'pass' => 'required|max:20',
]);

那么如何在此处为上面验证的每个字段直接发送消息?比如“你忘了电子邮件地址”和“需要密码”?

(如果没有为一个简单的任务编写一个火星漫游者程序。如同通常的laravel 5工匠的东西使新东西无用,添加2个命名空间,3个中间件,5个类,7个函数然后最后覆盖错误消息!!)

[编辑] 在得到以下答案和堆栈上的其他搜索的一些帮助后,我发现了要做的事情:

  1. 为每个字段的type验证添加消息: $validator = Validator::make($this->req->all(), [ 'email_add' => 'required|email|max:100', 'pass' => 'required|max:20', ], [ 'email_add.required' => 'The Email Address is actually required dude!', 'email_add.email' => 'The Email Address is is not a valid Email Address!' ]);

  2. 要将email_add更改为Email Address,即Attribute Name,而不是为每个字段上应用的每个验证都编写自定义消息: Validator::make(....)->setAttributeNames( [ 'email_add'=>'Email Address', 'pass'=>'Password' ]);

  3. 感谢帮助人员。

3 个答案:

答案 0 :(得分:1)

try this its work for you

$validator = Validator::make($this->req->all(), [
'email_add' => 'required|email|max:100',
'pass' => 'required|max:20',
]);

$messages = [
    'email_add.required'        => 'You forgot Email Address',
    'pass.required'   => 'Password is Required',

];

答案 1 :(得分:0)

To do so, add your messages to custom array in the resources/lang/xx/validation.php language file.

'custom' => [
    'email' => [
        'required' => 'We need to know your e-mail address!',
    ],
],

https://laravel.com/docs/5.1/validation#custom-error-messages

答案 2 :(得分:0)

if you want to change validation message for specific request you can put messages method within same request file like this

public function messages() {
   'name.required' => 'custom message',
   'email.required' => 'custom message for email',
   'email.email'   => 'custom message form email format'

}

Or if you want put validation message inside controller just pass third parameter as a message.