Creating Custom Validation Rules in Laravel 11

Creating Custom Validation Rules in Laravel 11

Laravel 11's strong validation mechanism, which imposes restrictions on submitted form data, makes ensuring data integrity easier. Although many typical circumstances are covered by the built-in rules, there are some situations that call for custom validation rules. This tutorial explains how to create custom validation rules in Laravel 11, enabling developers to adjust validation to the specific requirements of their application.

Creating a Custom Validation Rule Class

Use Laravel Artisan's command-line interface to quickly create a new custom validation rule class:

php artisan make:rule GoodPassword

Executing this command generates a class named GoodPasswordRule.php within the app/Rules directory.

Implementing the Custom Rule

Open the generated GoodPasswordRule.php class and articulate the custom validation logic:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class GoodPasswordRule implements Rule
{
    /**
     * Determine if the value is valid.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return strlen($value) >= 8 && preg_match('/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]/', $value);
    }

    /**
     * Get the validation error message for the rule.
     *
     * @param  string  $attribute
     * @return string
     */
    public function message($attribute)
    {
        return 'The :attribute must be at least 8 characters and include at least one uppercase letter, lowercase letter, number, and special character.';
    }
}

The passes method encapsulates the custom validation logic. In this illustration, it mandates a minimum password length and the presence of various character types. The message method specifies the error message exhibited when validation fails.

Utilizing the Custom Rule

Incorporate the custom validation rule within your form request class via the rules method:

public function rules()
{
    return [
        'password' => ['required', 'confirmed', new GoodPasswordRule],
    ];
}

Here, the GoodPasswordRule is assigned to the password field, guaranteeing compliance with the defined criteria.

Leveraging the Validation Request

In your controller method, associate the form request class with the request:

public function store(StoreUserRequest $request)
{
    // ... store user data ...
}

This binds the validation rules from the StoreUserRequest class to the incoming request, automatically initiating validation upon form submission.

Following these steps has allowed you to create and use a custom validation rule in Laravel 11, strengthening the data integrity of your application and improving user experience. Don't forget to modify the passes method's validation logic to meet your unique needs.


  • Date: