Custom Validation Rule in Laravel 5.5

Custom Validation Rule in Laravel 5.5

In this article, we will discuss writing custom validation rules in laravel 5.5. As you know that there are various default validation rules provided by laravel. But, in some cases, you may need to write your own validation rules and display a custom message to the user. Then, custom validation rules come to rescue us.

There was a slight change in writing custom validation rules in Laravel 5.4 and Laravel 5.5. In Laravel 5.4, we used to use custom validation using extend method on Validator facade. You can find more about it in its documentation.

In laravel 5.5, it has become more flexible. To use custom validation, we need to implement Illuminate\Contracts\Validation\Rule interface.

For example, let’s create a validation rule for our application.

Create Validation Rule

To create a validation rule, we need to run the following command.

This will create a new directory App/Rules and a new file inside it GenderValidationRule. This is where we will write our validation rules for checking gender.

Write Validation Logic

This class contains two methods passes() and message(). In passes() method, we will write our validation logic and inside message, we will write our error message to be displayed to the user.

Passes method receives two arguments i.e. $attributes and $value. The $attribute is the name of field from input and $value is the value of that input field. Another thing to keep in mind is that, it will only return boolean value: true or false only.

For this demo purpose, we will write validation for checking gender. We will only allow to Male, Female and Other in our input field. So, let’s write our first rule.

This is our validation rule, let’s create an error message upon failed validation. To do this, simply return the message you want to display to the user.

Thus, our GenderValidationRule.php looks like below:

Using the Rule

After we have defined our custom validation rules, we can directly use it in our controller by instantiating it in validate method. Thus, our validation in controller file looks like below:

Force Rule

Another point to remember is that these custom validation rules will not run when gender field is empty in form request. If you want to force the rule to check, you can implements ImplicitRule interface as like below example:

That is all for custom validation rule in laravel 5.5. If you have any further queries, please don’t forget to leave a comment.