How to Create a Custom Validation Rule in Laravel 12

Laravel, one of the most popular PHP frameworks, offers a robust validation system out of the box. However, there are times when you need to create custom validation rules to meet specific requirements. In this blog post, we'll walk through the process of creating a custom validation rule in Laravel 12, from setting up the project to running it. By the end of this guide, you'll have a solid understanding of how to implement custom validation rules in your Laravel applications.
Step 1: Setting Up the Laravel Project
To get started, we need to create a new Laravel project. Open your terminal and run the following command:
Laravel new custom-validation-rule
cd custom-validation-rule
This command will create a new Laravel project named custom-validation-rule.
Step 2: Creating a Custom Rule File
Next, we'll create a custom validation rule. Laravel provides an Artisan command to generate custom rule classes. Run the following command to create a custom rule named PasswordStrength:
php artisan make:rule PasswordStrength
This command will generate a new rule class in the app/Rules directory. Open the generated file and update it to define the validation logic. For example, you might want to enforce a strong password policy:
<?php
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
class PasswordStrength implements ValidationRule
{
/**
* Run the validation rule.
*
* @param \Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString $fail
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (! preg_match('/[A-Z]/', $value)) {
$fail('The :attribute must contain at least one capital letter.');
}
if (! preg_match('/[0-9]/', $value)) {
$fail('The :attribute must contain at least one number.');
}
if (! preg_match('/[^A-Za-z0-9]/', $value)) {
$fail('The :attribute must contain at least one symbol.');
}
}
}
Step 3: Creating a Form Request File
To handle validation in a more organized way, we'll create a form request class. Run the following command to generate a form request named UserRequest:
php artisan make:request UserRequest
This command will create a new form request class in the app/Http/Requests directory. Open the generated file and update it to use the custom PasswordStrength rule:
<?php
namespace App\Http\Requests;
use App\Rules\PasswordStrength;
use Illuminate\Foundation\Http\FormRequest;
class UserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'email' => ['required', 'string'],
'password' => ['required', 'string', new PasswordStrength],
];
}
}
Step 4: Creating a Controller
Now, we'll create a controller to handle user-related actions. Run the following command to generate a controller named UserController:
php artisan make:controller UserController
This command will create a new controller in the app/Http/Controllers directory. Open the generated file and add a method to handle user registration:
<?php
namespace App\Http\Controllers;
use App\Http\Requests\UserRequest;
class UserController extends Controller
{
public function create()
{
return view('user.create');
}
// Handle form submission
public function store(UserRequest $request)
{
$data = $request->validated();
// Logic to store the user or process it
return redirect()->route('user.create')->with('success', 'User created successfully!');
}
}
Step 5: Creating Routes
Next, we need to define routes to handle user registration. Open the routes/web.php file and add the following route:
<?php
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::get('/user/create', [UserController::class, 'create'])->name('user.create');
Route::post('/user/store', [UserController::class, 'store'])->name('user.store');
Step 6: Creating a View File
To allow users to register, we'll create a view file. Create a new file named create.blade.php in the resources/views/user directory and add the following form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create User</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header bg-primary text-white text-center">
<h4>Create User</h4>
</div>
<div class="card-body">
@if (session('success'))
<div class="text-success">{{session('success')}}</div>
@endif
<form action="{{route('user.store')}}" method="post">
@csrf
<div class="mb-3">
<label for="email" class="form-label">Email</label>
<input type="email" name="email" class="form-control" id="email" value="{{old('email') ?? ''}}" placeholder="Enter your email" />
@error('email')
<div class="text-danger">{{$message}}</div>
@enderror
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" name="password" class="form-control" id="password" value="{{old('password') ?? ''}}" placeholder="Enter your Password" />
@error('password')
<div class="text-danger">{{$message}}</div>
@enderror
</div>
<button type="submit" class="btn btn-primary w-100">Submit</button>
</form>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
Step 7: Running the Project
Finally, start the Laravel development server by running the following command:
php artisan serve
Visit http://127.0.0.1:8000/user/create in your browser, and you should see the registration form. Try submitting the form with different passwords to see the custom validation rule in action.
Conclusion
In this blog post, we've walked through the process of creating a custom validation rule in Laravel. We started by setting up a new Laravel project, created a custom rule, and used it in a form request. We also created a controller, defined routes, and set up a view to test our custom validation. By following these steps, you can easily implement custom validation rules in your Laravel applications to meet your specific requirements.
Happy coding! 🚀