How to Create a Custom Validation Rule in Laravel

How to Create a Custom Validation Rule in Laravel

Laravel ships with a long list of validation rules, but sooner or later you need one that doesn't exist. In this article I'll show how I create custom validation rules in current Laravel versions, using rule objects and closures.

Generate a rule class

The cleanest way is a rule object. Artisan creates it for you:

php artisan make:rule Uppercase

This creates app/Rules/Uppercase.php. The class implements the ValidationRule interface, which has a single validate method.

Write the validation logic

Inside validate you check the value and call $fail with a message when it isn't valid:

<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

class Uppercase implements ValidationRule
{
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (strtoupper($value) !== $value) {
            $fail('The :attribute must be uppercase.');
        }
    }
}

The :attribute placeholder is replaced with the field name, just like in Laravel's built-in messages.

Use the rule

Pass an instance of the class together with other rules:

use App\Rules\Uppercase;

$request->validate([
    'name' => ['required', 'string', new Uppercase],
]);

It works the same way in a Form Request's rules() method.

Rules with parameters

If your rule needs configuration, accept it in the constructor:

class MaxWords implements ValidationRule
{
    public function __construct(private int $max) {}

    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (str_word_count($value) > $this->max) {
            $fail("The :attribute may not have more than {$this->max} words.");
        }
    }
}
'bio' => ['required', new MaxWords(50)],

Translated error messages

Instead of a hard-coded string, you can pass a translation key and call translate():

$fail('validation.uppercase')->translate();

Then add the uppercase key to your lang/en/validation.php file. If the lang directory doesn't exist yet, publish it with php artisan lang:publish.

Quick one-off rules with closures

When a rule is only used once, a closure is enough:

$request->validate([
    'title' => [
        'required',
        function (string $attribute, mixed $value, Closure $fail) {
            if ($value === 'foo') {
                $fail("The {$attribute} is invalid.");
            }
        },
    ],
]);

For anything reused across the app, I prefer a rule class: it's easier to test and keeps controllers clean.

Implicit rules

By default, custom rules don't run when the field is missing or empty. If your rule must run even then, generate it with the --implicit flag:

php artisan make:rule Uppercase --implicit

Keep in mind an implicit rule only implies the field is required; whether it actually fails an empty value is up to your logic.

Tagged

No comments yet

Leave a comment

Security code

Comments are checked before they appear. See the privacy policy for how your data is used.