How to add a custom rule to validate strings in Laravel.

Ariel Mejia Dev
Ariel Mejia Dev
Published in
2 min readNov 28, 2019

In many cases it is useful to create a validation so that the texts sent by a request have a certain format, this task is extremely simple in Laravel, even if there is no type of validation like this in the validation rules in the framework.

Laravel provides us with a command to create our custom rules, in this case I will create a specific rule for a text contain only lowercase as example:

php artisan make:rule Lowercase

file code:

/*** Determine if the validation rule passes.** @param  string  $attribute* @param  mixed  $value* @return bool*/public function passes($attribute, $value){return strtolower($value) === $value;}

In the method passes, you can add your own logic, in this example only return a boolean if condition is met, it compares the string given with strtolower function, this is a php native function to transform a string to lowercase so if the transformed string is equal to the string given, it returns true.

But what if the condition return false?

Laravel provide us with another method on this class the method message to set the message when the condition return false:

/*** Get the validation error message.** @return string*/public function message(){return ':attribute' . ' ' . __('Must be written in lower case');}

In this example, use the prefix: attribute that what you will do is return the name of the field sent in the request, as part of the text string that was sent with the error, so that this is clearer, it will show how it would look in a message with and without this prefix:

return ':attribute' . ' ' . __('Must be written in lower case');
// EXPECTED: title Must be written in lower case
//without prefix attribute
return 'Must be written in lower case';
// EXPECTED: Must be written in lower case

Then I concatenate a space and the rest of the message that I want to send with the error, however in this last text string I use a different syntax, this syntax is used by Laravel to show the texts entered as translations if in the resources / lang folder there is a different language and in the app / config.php file you change the language settings of the app.

--

--

Ariel Mejia Dev
Ariel Mejia Dev

Fullstack Web/Mobile Developer and Laravel enthusiast.