Creating Custom Validation Rules in Laravel

--

When building a web application in Laravel, form validation is an essential part of ensuring data integrity and user experience. Laravel offers a comprehensive validation system out-of-the-box, including many built-in rules. However, there are times when you may need a custom validation rule to handle specific requirements. In this blog post, we will walk you through creating custom validation rules in Laravel with a real-world example.

Step 1: Create a New Laravel Project (Optional)

If you don’t have an existing Laravel project to work with, you can create a new one by running the following command:

composer create-project --prefer-dist laravel/laravel custom-rule-example

Step 2: Create a Custom Validation Rule

To create a custom validation rule, you need to generate a new Rule class using the Artisan command:

php artisan make:rule StrongPassword

This command will create a new file called `StrongPassword.php` in the `app/Rules` directory.

Step 3: Implement the Custom Rule

Open the `StrongPassword.php` file and implement the custom rule by modifying the `passes` and `message` methods. In this example, we will create a rule that requires a strong password with at least eight characters, including at least one uppercase letter, one lowercase letter, one number, and one special character.

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class StrongPassword implements Rule
{
public function passes($attribute, $value)
{
$pattern = '/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^a-zA-Z\d]).{8,}$/';

return preg_match($pattern, $value) === 1;
}

public function message()
{
return 'The :attribute must be at least 8 characters long and include at least one uppercase letter, one lowercase letter, one number, and one special character.';
}
}

Step 4: Use the Custom Rule in a Form Request

Now that you have created the custom validation rule, you can use it in a Form Request. First, generate a new Form Request using the Artisan command:

php artisan make:request RegisterRequest

This command will create a new file called `RegisterRequest.php` in the `app/Http/Requests` directory. Open this file and add the custom `StrongPassword` rule to the validation rules:

<?php

namespace App\Http\Requests;

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

class RegisterRequest extends FormRequest
{
public function authorize()
{
return true;
}

public function rules()
{
return [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => ['required', 'string', 'confirmed', new StrongPassword()],
];
}
}

Step 5: Apply the Form Request to a Controller Method

To use the `RegisterRequest` in your application, apply it to a controller method. In this example, we will use the `register` method in the `Auth\RegisterController`:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Requests\RegisterRequest;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use App\Rules\StrongPassword;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

class RegisterController extends Controller
{
public function register(RegisterRequest $request)
{
event(new Registered($user = $this->create($request->validated())));

auth()->login($user);

return redirect(RouteServiceProvider::HOME);
}

protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}

Now your custom validation rule, StrongPassword, is implemented and integrated into your Laravel application. The registration form will validate user input to ensure the password meets the specified criteria. If the password does not meet the requirements, a custom error message will be displayed, providing a seamless user experience.

--

--

Manish Kumar, Owner @ TheCodersprint.com

Principal Software Engineer with 11 years in PHP and 6 in Laravel. I write about web dev on LinkedIn and Medium, exploring Docker and microservices