Laravel Extended Validation custom message

Ajeesh Joshy picture Ajeesh Joshy · May 4, 2015 · Viewed 12.5k times · Source

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 ?

Answer

lukasgeiter picture lukasgeiter · May 4, 2015

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);
});