At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

,

How To Create A Custom Validation Rule In Laravel

  • By Vignesh M
  • September 19, 2018
  • 1082 Views

Laravel is a great PHP framework, it changed the way we write code by borrowing the best practices from great tools like Symfony, Ruby on Rails and it’s been evolving with lot of best practices on its own.
On the go, Laravel also minimizes our boilerplate by providing a lot of helpers, functions, etc. Indeed, one of the major task in any project would be data validation, Laravel comes up with splendid move to validate our input data and it have plenty of built-in validation methods available. You can chain the validation methods to create the desired rule for your data which is great.
But sometimes the we might receive a business case which couldn’t be solved with the built in methods, on that case we have to create custom validation rules and we can reuse that in future. There are actually two ways available to create custom validation rules,

  1. Using Closure
  2. Using Extensions
  3. Using Rule Objects

We’ll create a validation rule to validate whether a person is senior citizen a.k.a is above 60 in age or not for our examples.

Related: Generate Charts And Graphs Using Laravel

 

Using Closures

Note : To copy a codeblock, click on the image.

This may be the simplest way to create custom validation rule, The closure function should be defined within the validation rules array and will receive three arguments, the name of the attribute, the value of the attribute and a $fail callback function which needs to be called if the validation has failed. Take a look at the below example.
Validation-closure
We created our own validation rule and it’ll take care of adding the error message we provided into the fail callback into the validation errors array. You can get the complete working code of the above method from here.
The only catch in this approach is, you can use this closure in only one place. Next time you need the same rule you may have to duplicate the code again. Worry not, Laravel has your back to avoid code duplication by providing two other reusable methods.

Using Extensions

In this method we’ll register our validation rule in AppServiceProvider’s (Technically any service provider) boot method by extending the validation facade like below.
Validation-extend
You can also simplify extending method by giving a class name and method as the second argument like below.
Validation-Extend-short
You can use this rule just like any other built-in validation rule like below,


You can get the complete code of the above sample from here. This way of creating custom validator makes the logic reusable and clean but I personally feel that we’re polluting the AppServiceProivder. Imagine you have 10+ rules on the boot method. That brings us to the last and my favorite way of creating a custom validation rule.

Best To Read: Laravel API – How to Build REST API with Laravel 5.5 / Laravel 5.6

 

Using Rule Objects

Using artisan tool we can generate a Rule object and then use it in our validation rules array, run the following command in your terminal to create a rule object.

Once the command has ran, a new rule file will be created in your app/Rules folder open the file and add your validation logic in the passes method.

<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Lang;
class seniorCitizen implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return $value >= 60;
    }
    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must be 60 or above';
    }
}

By this way we’re not polluting the appServiceProvider and we still keep the reusability and extensibility of a class. You should use this rule object a little differently than normal like below,
Rule object usage
You  can get the complete working code of the above method from here
We’ve seen all three methods available in Laravel to create a custom validation rule. Hope this helps you to create quick and easy way to define custom validation rule in Laravel. Start trying it out and post us your experience and also your queries if you have any problems while trying this. Parallely, you can find the complete code samples I used in this blog here
Liked it? Then join us on the excursion of exploring Technologies subscribe us  to get more blogs & updates on latest technologies. Agira Technologies one of the fastest growing Web and Mobile Development Company in India. Precisely, extends its research on Web technologies, Mobile Apps, Blockchain, Chatbot, Artificial Intelligence, iOT and lot more. Explore more about us on www.agiratech.com.
For any inquiries reach us at info@agiratech.com

Vignesh M

An energetic Fullstack developer/Tech Lead and has a strong desire in Programming. With 6.5 years of experience in Angular, Javascript, Laravel PHP, Ionic, and Flutter, he always strives to come up with Smart Solutions to accomplish complex tasks.He is also interested in Video games, Motorcycles, Books, Movies, History.