0
0
LaravelHow-ToBeginner · 4 min read

How to Create Custom Validation Rule in Laravel Easily

In Laravel, you create a custom validation rule by making a new rule class with php artisan make:rule and defining the passes and message methods. Then, use this rule in your validation logic by referencing the rule class.
📐

Syntax

To create a custom validation rule in Laravel, you use the artisan command to generate a rule class. This class must have two methods:

  • passes($attribute, $value): Returns true if the value passes validation, otherwise false.
  • message(): Returns the error message shown when validation fails.

You then use this rule class in your validator by passing an instance of it.

bash and php
php artisan make:rule CustomRule

// In app/Rules/CustomRule.php
namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class CustomRule implements Rule
{
    public function passes($attribute, $value)
    {
        // Your validation logic here
        return true; // or false
    }

    public function message()
    {
        return 'The :attribute is invalid.';
    }
}
💻

Example

This example creates a custom rule that checks if a string contains the word 'hello'. It then uses this rule in a controller to validate input.

php
<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class ContainsHello implements Rule
{
    public function passes($attribute, $value)
    {
        return strpos($value, 'hello') !== false;
    }

    public function message()
    {
        return 'The :attribute must contain the word "hello".';
    }
}

// Usage in a controller method
use App\Rules\ContainsHello;
use Illuminate\Http\Request;

public function store(Request $request)
{
    $validated = $request->validate([
        'greeting' => ['required', new ContainsHello],
    ]);

    // Proceed with $validated data
    return 'Validation passed!';
}
Output
If input 'greeting' contains 'hello', output: Validation passed! If not, error: The greeting must contain the word "hello".
⚠️

Common Pitfalls

Common mistakes when creating custom validation rules include:

  • Not returning a boolean from passes method.
  • Forgetting to return a meaningful error message in message.
  • Not importing the rule class correctly when using it in validation.
  • Using the rule class without instantiating it (missing new keyword).
php
<?php
// Wrong: passes returns string instead of boolean
public function passes($attribute, $value)
{
    return 'yes'; // Incorrect
}

// Right: passes returns boolean
public function passes($attribute, $value)
{
    return $value === 'expected';
}

// Wrong: using rule class without new
$request->validate([
    'field' => [ContainsHello], // Incorrect
]);

// Right: instantiate the rule
$request->validate([
    'field' => [new ContainsHello],
]);
📊

Quick Reference

Summary tips for custom validation rules in Laravel:

  • Use php artisan make:rule RuleName to generate the rule class.
  • Implement passes to define validation logic returning true or false.
  • Implement message to provide a clear error message.
  • Use the rule by creating a new instance in your validation array.
  • Test your rule with different inputs to ensure correctness.

Key Takeaways

Create a custom rule class with artisan and implement passes() and message() methods.
passes() must return true or false based on your validation logic.
Use the custom rule by instantiating it in your validation rules array.
Provide a clear error message in message() for user feedback.
Avoid common mistakes like forgetting to instantiate the rule or returning wrong types.