I'm using laravel 5.1. I have a summernotejs form element. I've created a custom validation rule successfully, which takes the HTML provided from the form input, strips the tags, and does a strlen()
call on the text content. Therefore I can see the length of a message without any tags in it.
This is my validation rule:
Validator::extend('strip_min', function ($attribute, $value, $parameters, $validator) {
return strlen(strip_tags($value)) >= $parameters[0];
});
I call the validation rule by specifying: strip_min:10
or strip_min:20
etc, with the number being the minimum string length after stripping tags.
I want to add a custom message, saying that the content lengths needs to be a minimum of n
characters long.
The Laravel documentation on this aspect is useless. I've opened my validation.php
file, which contains all the error messages.
I've added the key strip_min
to the message array, with the message: The :attribute must be at least :min characters.
When I test it, I get the error message:
The notice must be at least :min characters.
How can I convert :min
into the number specified in the validation rule?! I've read the documentation but it's all over the place, and I cant understand how to just simply replace :min with the given number.
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.
Customizing Validation Rules Using Laravel. Share. While you are working with user input and forms, validating the common fields and extracting the exact validation rules makes the code easier to maintain and read. You can make the code powerful by using the Laravel custom validation rule with parameters.
Found out.
Validator::extend('strip_min', function ($attribute, $value, $parameters, $validator) {
$validator->addReplacer('strip_min', function($message, $attribute, $rule, $parameters){
return str_replace([':min'], $parameters, $message);
});
return strlen(strip_tags($value)) >= $parameters[0];
});
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