Create custom Laravel validation rule

Create custom Laravel validation rule

There are multiple ways to apply validation to a Laravel form. Also there are many validation rules that come with the framework. The validation rules cover almost all requirements for a website.

Sometimes clients come up with unique validation rules to help their users. So in that case, as always Laravel provides a way to customise to satisfy the particular validation needs of a website.

First use the following command to create custom rule class

php artisan make:rule NewCustomRule

This command will create a rule class, app/Rules/NewCustomRule.php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class NewCustomRule implements Rule
{

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

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
      return 'The validation error message.';
    }
}

In the above custom validation rule class we have two methods. The passes method is for validation logic. We can add any validation logic here with value property.

The passes method will return TRUE/FALSE according to your logic. The message method is for the validation error message to be shown in form.

Checkout this example validation for an even number input:

public function passes($attribute, $value)
{
    return $value % 2 == 0;
}
public function message()
{
    return ':attribute should be an even number';
}

We can use this created custom validation rule in controller by passing in validate method:

public function store(Request $request)
{
    $this->validate($request, ['even' => new NewCustomRule]);
}

Custom validations are very useful when there are requirements for complex validation conditions. But it's great to see Laravel manages a lot of validation rules which can cover almost all of our requirements.