Laravel comes with many built-in validation rules like email, required, unique, and date. However, sometimes you need custom validation for specific requirements. In this tutorial, I’ll show you how to create a custom validation rule in Laravel 12.
We’ll implement a BirthYearRule that validates whether a user’s birth year falls between 1980 and the current year.
Step 1: Install Laravel 12
First, create a new Laravel 12 project:
composer create-project laravel/laravel example-app
Step 2: Set Up Routes
Add these routes to routes/web.php:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\CustomValidationController;
Route::get('custom-validation', [CustomValidationController::class, 'create']);
Route::post('custom-validation', [CustomValidationController::class, 'store'])->name('custom.validation.post');
Step 3: Create the Custom Validation Rule
Generate and implement the custom rule:
php artisan make:rule BirthYearRule
Update app/Rules/BirthYearRule.php:
<?php
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
class BirthYearRule implements ValidationRule
{
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if(!($value > 1980 && $value <= date('Y'))) {
$fail('The :attribute must be between 1980 and '.date('Y').'.');
}
}
}
Step 4: Create the Controller
Generate a controller and implement the validation logic:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
use App\Rules\BirthYearRule;
class CustomValidationController extends Controller
{
public function create(): View
{
return view('forms');
}
public function store(Request $request): RedirectResponse
{
$validatedData = $request->validate([
'name' => 'required',
'birth_year' => ['required', 'numeric', new BirthYearRule()],
]);
return back()->with('success', 'User created successfully.');
}
}
Step 5: Create the View
Create resources/views/forms.blade.php:
<!DOCTYPE html>
<html>
<head>
<title>Laravel Custom Validation Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="card mt-5">
<h3 class="card-header p-3">Laravel 12 Custom Validation Example</h3>
<div class="card-body">
@if(session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
@endif
<form method="POST" action="{{ route('custom.validation.post') }}">
@csrf
<div class="mb-3">
<label class="form-label">Name:</label>
<input type="text" name="name" class="form-control @error('name') is-invalid @enderror">
@error('name')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
<div class="mb-3">
<label class="form-label">Birth Year:</label>
<input type="text" name="birth_year" class="form-control @error('birth_year') is-invalid @enderror">
@error('birth_year')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
<div class="mb-3">
<button class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Run the Application
Start the development server:
php artisan serve
Visit http://localhost:8000/custom-validation in your browser to test the custom validation.