Custom Validation Rules in Laravel

custom validation rules laravel

In this post, we will look at how we can create custom validation rules for Laravel Form Requests. In our previous post, Laravel Form Request Demystified we looked at how we can extract the validation from controller to custom request class, today we will create custom rules to use in the request class.

Laravel provides an easy way to create custom validation rules. You can create custom rules based around your own business needs and use them anywhere in your application.

This post is the continutiy of Laravel Form Request Demystified post, so you should read this first.

Creating Rule Class

In the previous post, we created form request for a Customer model for name and emailattributes. In this post, we will add a custom rule for name propert. For the sake of this post, I assume that we want users to enter a upper case customer name in the name field.

You can create a custom Rule class in Laravel, using below command:

After running this command Laravel, create a new folder called Rules in app folder with a UpperCase class file with below content.

We have to add our custom logic in the passes() function and custom message for this rule in message() function.

Adding Validation Logic

Now, we will update our passes() function with below.

We are just checking that, if the value passed for validation is in upper case if it is, then this function will return a boolen value true otherwise false.

Next we will update the message() method with below:

This message will return a message if the validation fails.

Using the Validation Rule in Form Request Class

All set, now it’s time to add this rule to our form request class. Import the validation rule class in your request class using the use statement.

Update your StoreCustomerRequest‘s rules() function with below.

Note that we are adding the class itself to the name validation rules. Whenever form request run the validation rules, it will instantiate UpperCase class and validate the rule for this class.

Now, if you enter a lower case name in the Customer’s name field, you will get a custom message like:

The name must be uppercase.

Using the Validation Rule in Controller

You can also use the custom validation rule in your controller as well. Import the custom rule class UpperCase into the controller using use statement.

Then implement the validation in controller like below:

Conclusion

That’s it for now. In this post, we have learned how we can create custom rules for validation and use them in form request class and in controllers. You can read more about custom validation rules on Laravel’s Offical documentation.