Search code examples
phplaravellaravel-validation

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 ?


Solution

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