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 ?
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.
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.
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.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With