Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel custom validation message parameter

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.

like image 901
Phil Cross Avatar asked Oct 29 '15 12:10

Phil Cross


People also ask

What is the method used for specifying custom message for validation 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 custom validation in laravel?

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.


1 Answers

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];
});
like image 119
Phil Cross Avatar answered Sep 22 '22 23:09

Phil Cross