Laravel provides a robust validation system, but sometimes you may need to define custom validation rules to handle specific use cases. With Laravel 12, the process of creating custom validation rules has been streamlined with improved syntax and features.

In this article, we will explore how to create and use custom validation rules in Laravel 12.

Why Use Custom Validation Rules?

While Laravel’s built-in validation rules cover most scenarios, there are cases where you need more flexibility. For example:

  • Validating a username to ensure it doesn’t contain special characters.
  • Checking if a value exists in an external API.
  • Enforcing complex business logic.

Custom validation rules allow you to encapsulate this logic in a reusable and testable way.

Creating a Custom Validation Rule

In Laravel 12, you can create a custom validation rule using the `make:rule` Artisan command:

php artisan make:rule ValidUsername

This command generates a new rule class in the `app/Rules` directory:

// filepath: /app/Rules/ValidUsername.php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class ValidUsername implements Rule

{

public function __construct()

{

// Initialization logic (if needed)

}

public function passes($attribute, $value): bool

{

// Validation logic: Ensure the username contains only letters and numbers

return preg_match('/^[a-zA-Z0-9]+$/', $value);

}

public function message(): string

{

// Custom error message

return 'The :attribute must contain only letters and numbers.';

}

}

Explanation:

  • The `passes` method contains the validation logic. It returns `true` if the validation passes and `false` otherwise.
  • The `message` method defines the error message that will be displayed if validation fails.

Using the Custom Rule in a Form Request

To use the custom rule, you can include it in a form request class. For example:

// filepath: /app/Http/Requests/StoreUserRequest.php
namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use App\Rules\ValidUsername;

class StoreUserRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'username' => ['required', 'string', 'max:255', new ValidUsername()],
            'email' => ['required', 'email', 'unique:users,email'],
            // ...other rules...
        ];
    }
}

Explanation:

  • The `ValidUsername` rule is applied to the `username` field.
  • You can combine the custom rule with other built-in validation rules.

Using the Custom Rule Inline

If you don’t want to create a separate class, you can define a custom rule inline using a closure:

$request->validate([
    'username' => [
        'required',
        'string',
        'max:255',
        function ($attribute, $value, $fail) {
            if (!preg_match('/^[a-zA-Z0-9]+$/', $value)) {
                $fail('The ' . $attribute . ' must contain only letters and numbers.');
            }
        },
    ],
]);

When to Use:

  • Inline rules are useful for simple, one-off validations.
  • For reusable or complex logic, prefer creating a dedicated rule class.

Testing the Custom Rule

Laravel makes it easy to test custom validation rules. Here’s an example of how to test the `ValidUsername` rule:

// filepath: /tests/Unit/Rules/ValidUsernameTest.php
namespace Tests\Unit\Rules;

use Tests\TestCase;
use App\Rules\ValidUsername;

class ValidUsernameTest extends TestCase
{
    public function test_valid_username_passes()
    {
        $rule = new ValidUsername();

        $this->assertTrue($rule->passes('username', 'ValidUser123'));
    }

    public function test_invalid_username_fails()
    {
        $rule = new ValidUsername();

        $this->assertFalse($rule->passes('username', 'Invalid@User!'));
    }
}

Explanation:

  • The `test_valid_username_passes` method ensures the rule passes for valid usernames.
  • The `test_invalid_username_fails` method ensures the rule fails for invalid usernames.

Benefits of the Laravel 12 Syntax

  • Improved Readability: The `passes` and `message` methods make the rule logic clear and concise.
  • Reusability: Custom rules can be reused across multiple form requests or controllers.
  • Testability: Encapsulating validation logic in a class makes it easy to write unit tests.

Conclusion

Custom validation rules in Laravel 12 provide a powerful way to handle complex validation scenarios. Whether you’re enforcing unique business rules or validating data against external APIs, Laravel’s validation system makes it easy to extend and customize.

Start using custom validation rules today to make your Laravel applications more robust and maintainable!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Quote of the week

"People ask me what I do in the winter when there's no baseball. I'll tell you what I do. I stare out the window and wait for spring."

~ Rogers Hornsby

All rights resolved