In this article, I’ll demonstrate how to create custom validation rules in Laravel 11. While Laravel offers built-in validation mechanisms that expedite web application development, there are times when you need to implement custom validation rules that extend beyond the default options to meet specific requirements. Let see the Laravel Custom Validation Error Message Tutorial step by step.
Step 1: Set Up Routes
Modify the routes/web.php
file to include routes for handling form submissions:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FormController;
Route::get('users/create', [FormController::class, 'create']);
Route::post('users/create', [FormController::class, 'store'])->name('users.store');
Step 2: Create a Controller
Generate a new controller using the following command:
php artisan make:controller FormController
Next, edit the app/Http/Controllers/FormController.php
file to include methods for displaying the form and processing form data:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
class FormController extends Controller
{
/**
* Show the form for creating a new user.
*
* @return \Illuminate\View\View
*/
public function create(): View
{
return view('my_form');
}
/**
* Store a newly created user in the database.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse
*/
public function store(Request $request): RedirectResponse
{
$validatedData = $request->validate([
'name' => 'required',
'password' => 'required|min:5',
'email' => 'required|email|unique:users'
], [
'name.required' => 'The name field is mandatory.',
'password.required' => 'The password field cannot be empty.',
'email.required' => 'The email field is necessary.',
'email.email' => 'Please provide a valid email address.'
]);
$validatedData['password'] = bcrypt($validatedData['password']);
User::create($validatedData);
return back()->with('success', 'User successfully created.');
}
}
Step 3: Create the Form View
In the resources/views
directory, create a my_form.blade.php
file with the following HTML form:
<!DOCTYPE html>
<html>
<head>
<title>Laravel 11 Custom Form Validation Guide - ItcodStuff.com</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
</head>
<body>
<div class="container">
<div class="card mt-5">
<h3 class="card-header p-3"><i class="fa fa-star"></i> Laravel 11 Custom Form Validation Guide - ItcodStuff.com</h3>
<div class="card-body">
@if (session('success'))
<div class="alert alert-success" role="alert">
{{ session('success') }}
</div>
@endif
<!-- Display All Error Messages -->
@if ($errors->any())
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some issues with your submission.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form method="POST" action="{{ route('users.store') }}">
{{ 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">
<!-- Display Specific Error Message -->
@error('name')
<span class="text-danger">{{ $message }}</span>
@enderror
</div>
<div class="mb-3">
<label class="form-label" for="inputPassword">Password:</label>
<input
type="password"
name="password"
id="inputPassword"
class="form-control @error('password') is-invalid @enderror"
placeholder="Password">
<!-- Display Specific Error Message -->
@if ($errors->has('password'))
<span class="text-danger">{{ $errors->first('password') }}</span>
@endif
</div>
<div class="mb-3">
<label class="form-label" for="inputEmail">Email:</label>
<input
type="text"
name="email"
id="inputEmail"
class="form-control @error('email') is-invalid @enderror"
placeholder="Email">
@error('email')
<span class="text-danger">{{ $message }}</span>
@endif
</div>
<div class="mb-3">
<button class="btn btn-success btn-submit"><i class="fa fa-save"></i> Submit</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Step 4: Run the Application
Start the application server using:
php artisan serve
Then, open your browser and navigate to http://localhost:8000/users/create
to test the application.