Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Extended Validation custom message

I wanted to create this extended 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.  
}

I would use this rule like this

'my_field' => 'required|my_custom_validation_rule',

I want to use some dynamic message for the error of "my_custom_validation_rule"

I was unable to find something from the documentation about it. Is there anyway to do it ?

like image 274
Ajeesh Joshy Avatar asked May 04 '15 07:05

Ajeesh Joshy


People also ask

What is the method used for specifying custom messages for validator errors in form request?

After checking if the request failed to pass validation, you may use the withErrors method to flash the error messages to the session. When using this method, the $errors variable will automatically be shared with your views after redirection, allowing you to easily display them back to the user.

How do you validate exact words in laravel?

To get the exact words to validate you can make use of Rule::in method available with laravel. Using Rule::in method whatever the values provided by this rule has to be matched otherwise it will fail.

What is the method used to configure validation rules in form request?

Laravel Form Request class comes with two default methods auth() and rules() . You can perform any authorization logic in auth() method whether the current user is allowed to request or not. And in rules() method you can write all your validation rule.


1 Answers

The extend method allows to pass the message as a third argument:

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

By default you can only use dynamic variable, which is :attribute. If you want to add more use Validator::replacer():

Validator::replacer('my_custom_validation_rule', function($message, $attribute, $rule, $parameters){
    return str_replace(':foo', $parameters[0], $message);
});
like image 168
lukasgeiter Avatar answered Oct 08 '22 04:10

lukasgeiter