How to create custom validation rules in laravel ?

Laravel provides large set of validation rules. We can use these rules while validating the data passed through request. From the official documentation , we can see available validation rules.

Available Validation Rules in Laravel

Although there are large number of rules, sometime these rules may not sufficient for our requirement and we might need custom requirement for validation. In order to solve such problem, laravel provides elegant way to create custom validation rule with few lines of code.

For example, we have to validate form input filed as a palindrome or not, then we have to create a rule class with following artisan command.

The above command will create a Palindrome class inside app/Rules/ directory something like following.

Here, We have to write logic inside passes function for validation and error message inside message function to return error message in case of failed validation.

Now, we will add some logic to check request parameter is palindrome or not.

Here, $attribute is the parameter under validation and $value is the parameter value. We just checked whether reverse of the value is same as value inside passes function. The function will return true if $value is palindrome and false otherwise. We also changed the error message in message function.

Till now, we have created a validation rule that checks a request parameter as palindrome or not. Now, we will see how to use this rule while validating the request.

Display Custom Validation Error Message in Laravel

Usage

Case I

If you want to write validation logic in the controller then you can use above rule like this:

Case II

If you have made request class for the validation then you can use the rule like this:

In this way, you can create custom validation rule and use it for the validation of request parameter. Making own custom rule allows us to validate the request parameter to fulfill our own validation requirement in more structured way when available validation rules are not sufficient for our requirement.


sagautam5

sagautam5

Computer Enginner, A Laravel Developer,
http://sagargautam.stacklearning.com

Leave a Reply

Your email address will not be published. Required fields are marked *