How to Create Custom Validation Rules in Laravel 11?

08-Mar-2024

.

Admin

How to Create Custom Validation Rules in Laravel 11?

Hi Dev,

This tutorial is dedicated to illustrating an example of a custom validation rule in Laravel. It aims to help you grasp the process of crafting and incorporating your own validation rules into Laravel applications. Below, you'll find a step-by-step explanation of how to create a custom validation rule.

While Laravel comes equipped with default validation rules such as email, required, unique, and date, there are instances where you might need to define your own custom rules. In this tutorial, we'll delve into the creation of a custom validation rule named BirthYearRule.

For the purpose of this example, let's imagine a scenario where we want to validate user input for a birth year. We'll introduce an input text box for the birth_year field and enforce validation to ensure that the user inputs a year between 1980 and the current year, leveraging our custom validation rule. This guide will walk you through the necessary steps to achieve this in Laravel.

So, let's star following example:

Generating the Rule Class


Employ the Laravel Artisan command to quickly create a new custom validation rule class:

php artisan make:rule StrongPassword

This command creates a class named StrongPasswordRule.php within the app/Rules directory.

Implementing the Custom Rule

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class StrongPasswordRule 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.';

}

}

Utilizing the Custom Rule

public function rules()

{

return [

'password' => ['required', 'confirmed', new StrongPasswordRule],

];

}

Here, the StrongPasswordRule is applied to the password field, ensuring it adheres to 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 triggering validation when the form is submitted.

#Laravel 11