Laravel 12 Validation Form Rules Explained: A Complete Guide with Examples
Validations are crucial in web applications to ensure that user-submitted data is correct, secure, and follows business rules. Laravel provides a simple yet powerful way to validate incoming data.
In this guide, we’ll cover:
✅ Basic Form Request Validation
✅ Custom Validation Rules
✅ Real-Time Validation with Livewire (Optional)
✅ Error Handling & Displaying Messages
Let’s dive in!
1. Why Validations Are Important?
Before processing user input, we must check:
- Required fields are not empty.
- Emails are in the correct format.
- Passwords meet security requirements.
- File uploads are within allowed size and type.
Laravel makes this easy with built-in validation features.
2. Basic Validation in Laravel 12
A. Using validate() in Controllers
The simplest way is to validate directly in a controller.
Example: Validating a Registration Form
use Illuminate\Http\Request;
public function register(Request $request)
{
// Validate the request
$validated = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users',
'password' => 'required|min:8|confirmed',
]);
// If validation passes, create user
User::create($validated);
return redirect('/dashboard')->with('success', 'Registration successful!');
}
Explanation of Rules:
| Rule | Meaning |
|---|---|
required |
Field must not be empty |
string |
Must be a text value |
max:255 |
Maximum 255 characters |
email |
Must be a valid email |
unique:users |
Email must not exist in users table |
min:8 |
Minimum 8 characters |
confirmed |
Requires matching password_confirmation field |
❌ If validation fails, Laravel automatically redirects back with errors.
B. Displaying Validation Errors in Blade
Laravel stores errors in the $errors variable (available in Blade).
<form method="POST" action="/register">
@csrf
<!-- Name Field -->
<div>
<label>Name</label>
<input type="text" name="name" value="{{ old('name') }}">
@error('name')
<span style="color: red;">{{ $message }}</span>
@enderror
</div>
<!-- Email Field -->
<div>
<label>Email</label>
<input type="email" name="email" value="{{ old('email') }}">
@error('email')
<span style="color: red;">{{ $message }}</span>
@enderror
</div>
<!-- Password Field -->
<div>
<label>Password</label>
<input type="password" name="password">
@error('password')
<span style="color: red;">{{ $message }}</span>
@enderror
</div>
<!-- Confirm Password -->
<div>
<label>Confirm Password</label>
<input type="password" name="password_confirmation">
</div>
<button type="submit">Register</button>
</form>
Key Points:
✔ old('field') repopulates form data after validation fails.
✔ @error('field') displays validation errors.
3. Advanced Validation: Form Request Classes
Instead of cluttering controllers, Laravel allows dedicated validation classes.
Step 1: Create a Form Request
php artisan make:request RegisterUserRequest
Step 2: Define Rules in rules() Method
public function rules()
{
return [
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users',
'password' => 'required|min:8|confirmed',
];
}
Step 3: Use in Controller
public function register(RegisterUserRequest $request)
{
// Validation passed automatically!
User::create($request->validated());
return redirect('/dashboard');
}
✅ Benefits:
✔ Cleaner controllers
✔ Reusable validation logic
4. Custom Validation Rules
Sometimes, built-in rules aren’t enough. Let’s create a custom rule.
Example: Check if a Username is "Admin" (Forbidden)
php artisan make:rule ForbiddenUsername
Now, edit app/Rules/ForbiddenUsername.php:
public function passes($attribute, $value)
{
return strtolower($value) !== 'admin';
}
public function message()
{
return 'The :attribute cannot be "admin".';
}
Using the Custom Rule
use App\Rules\ForbiddenUsername;
$request->validate([
'username' => ['required', new ForbiddenUsername],
]);
5. Real-Time Validation (Optional with Livewire)
For a smoother UX, validate fields as the user types using Laravel Livewire.
Example: Instant Email Validation
use Livewire\Component;
class RegisterForm extends Component
{
public $email;
public function updatedEmail()
{
$this->validateOnly('email', [
'email' => 'required|email|unique:users',
]);
}
public function render()
{
return view('livewire.register-form');
}
}
Now, errors appear instantly without page reload!
6. Common Validation Rules Cheat Sheet
| Rule | Example | Description |
|---|---|---|
required |
'name' => 'required' |
Field must be filled |
email |
'email' => 'email' |
Must be a valid email |
min:8 |
'password' => 'min:8' |
Minimum 8 characters |
max:255 |
'title' => 'max:255' |
Maximum 255 chars |
confirmed |
'password' => 'confirmed' |
Needs password_confirmation |
unique:users |
'email' => 'unique:users' |
Must not exist in DB |
file |
`'photo' => 'file | max:2048'` |
date |
'dob' => 'date' |
Must be a valid date |
Conclusion
Laravel validations are easy yet powerful!
Key Takeaways:
✔ Use $request->validate() for quick checks.
✔ Form Request classes keep controllers clean.
✔ Custom rules handle unique business logic.
✔ Livewire enables real-time validation.
🚀 Now go ahead and secure your Laravel forms!
Projects to explore next
Source-code projects from the KritiMyantra catalogue. Check each project's details before buying.
Flask Authentication System (Free Version) - Kritim Yantra
🛠 Features✔ Google & GitHub Authentication✔ User Registration & Login✔ Profile/Dashboard Access✔ Secure & Mi...
Flask Blog CMS with Admin Dashboard — Python Source Code
A Flask-based blogging website with a built-in admin dashboard. Manage articles, images, categories, tags and featured p...
Laravel 12 + ReactJS Starter Kit: Add Multi-Language Support (Arabic, English, Spanish) with Blog CRUD
🚀 Installation & Setup Download & Extract Get the ZIP from kritimyantra.com and extract it. Includes preconfigu...
Comments
No comments yet. Be the first to comment.
Sign in to join the discussion.