Custom Validation Rules in Laravel

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.

  • 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
  • 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.

  • 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.';
    }
}
  • 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()],
        ];
    }
}
  • 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.

Share this:

user

Author: Manish Kumar

I've been working with PHP for over 11 years and focusing on Laravel for the last 6 years. During this time, I've taken part in big projects and gotten to know tools like Laravel Livewire really well. Besides working on projects, I enjoy writing about Laravel on LinkedIn and Medium to share what I've learned. I'm always looking to learn more and share my knowledge with others. Right now, I'm diving into new areas like using Docker to make web apps run better and exploring how to build them using microservices. My goal is to keep learning and help others do the same in the world of web development.

Leave a reply

dot

Subscribe to Newsletter

Provide your email to get email notification when we launch new products or publish new articles

Newsletter

Subscribe to my newsletter to get updated posts

Don't worry, I don't spam