Jun 13, 2024 | Laravel 11 Laravel
Hello Dev,
While Laravel comes with a robust set of default validation rules like email, required, unique, and date, there are occasions when you may need to craft your own. I'll walk you through the process step by step.
In this example, let's fashion a custom validation rule named BirthYearRule. We'll incorporate an input text box for birth_year and ensure that users input a year between 1980 and the current year using our custom validation.
Steps to Create a Custom Validation Rule in Laravel 11:
Step 1: Install Laravel 11Ensure you have Laravel 11 installed. If not, you can install it using Composer.
Step 2: Create a RouteSet up a route to handle the form submission and validation.
Step 3: Create the Validation RuleDefine our custom validation rule, BirthYearRule, to check if the birth year falls within the specified range.
Step 4: Create a ControllerCreate a controller to handle the form submission and apply our custom validation rule.
Step 5: Create a View FileCraft a view file containing the form with an input field for the birth year.
Once these steps are completed, you'll have a Laravel application equipped with a custom validation rule ensuring that users provide a birth year within the designated range.
Step 1: Install Laravel 11If you haven't already, create a new Laravel project:
composer create-project laravel/laravel example-appStep 2: Create Route
Open the routes/web.php file and define a route for displaying the form and another for handling the form submission:
routes/web.php<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\CustomValidationController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('custom-validation', [CustomValidationController::class, 'create']); Route::post('custom-validation', [CustomValidationController::class, 'store'])->name('custom.validation.post');Read Also: Laravel 10 Import Export Excel and CSV File Example Tutorial Step 3: Create Validation Rule
Generate a custom validation rule using Artisan CLI:
php artisan make:rule BirthYearRule
This command creates a new rule class in the app/Rules directory. Open the generated BirthYearRule.php file and implement the logic for validating the birth year:
app/Rules/BirthYearRule.php<?php namespace App\Rules; use Closure; use Illuminate\Contracts\Validation\ValidationRule; class BirthYearRule implements ValidationRule { /** * Run the validation rule. * * @param \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { if(!($value > 1980 & $value < date('Y'))){ $fail('The :attribute must be between 1980 to '.date('Y').'.'); } } }Step 4: Create Controller
Create a controller to handle the form display and validation logic:
php artisan make:controller CustomValidationController
Add methods to show the form and validate the birth year:
app/Http/Controllers/CustomValidationController.php<?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 { /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function create(): View { return view('forms'); } /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function store(Request $request): RedirectResponse { $validatedData = $request->validate([ 'name' => 'required', 'birth_year' => [ 'required', new BirthYearRule() ] ]); /* $validatedData['password'] = bcrypt($validatedData['password']); $user = User::create($validatedData); */ return back()->with('success', 'User created successfully.'); }Step 5: Create View File
Create a Blade template for the form under resources/views/form.blade.php:
<!DOCTYPE html> <html> <head> <title>How to Create a Custom Validation Rule in Laravel 11? -- ItErrorSolution.com</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <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">How to Create a Custom Validation Rule in Laravel 11? -- ItErrorSolution.com</h3> <div class="card-body"> <form method="POST" action="{{ route('custom.validation.post') }}"> {{ csrf_field() }} <div class="mb-3"> <label class="form-label" for="inputName">Name:</label> <input type="text" name="name" id="inputName" class="form-control @error('name') is-invalid @enderror" placeholder="Name"> @error('name') <span class="text-danger">{{ $message }}</span> @enderror </div> <div class="mb-3"> <label class="form-label" for="inputEmail">Birth Year:</label> <input type="text" name="birth_year" id="inputEmail" class="form-control @error('birth_year') is-invalid @enderror" placeholder="Birth Year"> @error('birth_year') <span class="text-danger">{{ $message }}</span> @endif </div> <div class="mb-3"> <button class="btn btn-success btn-submit">Submit</button> </div> </form> </div> </div> </div> </body> </html>Step: Run the Application
Now, to run the Laravel application, please type the following command and press enter:
php artisan serve
Now, open your web browser and enter the provided URL to view the output of the application.
View Your Applicationhttp://localhost:8000/custom-validationOutput:
Thank you for your encouragement! If you have any questions or need further assistance, feel free to ask. I'm here to help!
"Hey there! I'm a full-stack developer and proud owner of ItErrorSolution.com, based right here in India. I love nothing more than sharing handy tips and tricks with my fellow developers through easy-to-follow tutorials. When it comes to coding, I'm all about PHP, Laravel, Angular, Vue, Node, JavaScript, jQuery, CodeIgniter, and Bootstrap – been hooked on them forever! I'm all about putting in the work and staying committed. Ready to join me on this journey to coding?"