2

Im trying to figure out how to quickly add error messages per field in Laravel 5. Here is what I got:

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

So how do I put a message directly here for each field validated above? like "You forgot Email Address" and "Password is Required"?

(How to that without writing a mars rover program for 1 simple task. Like the usualy laravel 5 stuff of artisan make new something useless, add 2 namespaces, 3 middlewares, 5 classes, 7 functions and then finally override error messages!!)


[EDIT] After some help from answers below and other search on stack, I found exactly what is to be done:

  1. Add a message for the type of validations per field: $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. To just change the email_add into Email Address, i.e. the Attribute Name instead of writing a custom msg for every validation applied on every field: Validator::make(....)->setAttributeNames( [ 'email_add'=>'Email Address', 'pass'=>'Password' ]);


Thanks for the help guyz.

Raheel Hasan
  • 5,753
  • 4
  • 39
  • 70
  • Please make sure you can't find the answer on the google or the stack. this is already question asked before you asked. but that is not necessary code same as you want. you need to do some manipulation with code. so be careful next time. – Yagnik Detroja Sep 01 '16 at 07:06

3 Answers3

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',

];
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

Shuvo
  • 113
  • 1
  • 8
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.

narayansharma91
  • 2,273
  • 1
  • 12
  • 20