0
0
Laravelframework~5 mins

Custom validation rules in Laravel

Choose your learning style9 modes available
Introduction

Custom validation rules let you check data in your own way when the built-in checks are not enough.

You want to check if a username is unique in a special way.
You need to validate a password with custom strength rules.
You want to verify a code format that Laravel does not support by default.
You want to reuse a complex validation logic in many places.
You want to keep your validation clean and organized.
Syntax
Laravel
php artisan make:rule RuleName

// Then in app/Rules/RuleName.php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class RuleName implements Rule
{
    public function passes($attribute, $value)
    {
        // return true if valid, false if not
    }

    public function message()
    {
        return 'The validation error message.';
    }
}

The passes method checks if the value is valid.

The message method returns the error message shown if validation fails.

Examples
This rule checks if the input is all uppercase letters.
Laravel
<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class Uppercase implements Rule
{
    public function passes($attribute, $value)
    {
        return strtoupper($value) === $value;
    }

    public function message()
    {
        return 'The :attribute must be uppercase.';
    }
}
Apply the custom rule by creating a new instance inside the validation array.
Laravel
// Using the rule in a controller
$request->validate([
    'name' => ['required', new Uppercase()],
]);
Sample Program

This example creates a rule to check if a number is even. The controller uses it to validate input.

Laravel
<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class EvenNumber implements Rule
{
    public function passes($attribute, $value)
    {
        return is_numeric($value) && $value % 2 === 0;
    }

    public function message()
    {
        return 'The :attribute must be an even number.';
    }
}

// In a controller method
public function store(Request $request)
{
    $request->validate([
        'number' => ['required', new EvenNumber()],
    ]);

    return 'Number is valid and even!';
}
OutputSuccess
Important Notes

You can pass extra data to your rule by adding a constructor.

Custom rules help keep validation logic reusable and clean.

Summary

Custom validation rules let you create your own checks for data.

They have two main methods: passes and message.

Use them in validation arrays by creating new instances.