Laravel 12 Validation Form Rules Explained: A Complete Guide with Examples

Author

Kritim Yantra

Mar 27, 2025

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!

LIVE MENTORSHIP ONLY 5 SPOTS

Laravel Mastery
Coaching Class Program

KritiMyantra

Transform from beginner to Laravel expert with our personalized Coaching Class starting June 11, 2025. Limited enrollment ensures focused attention.

Daily Sessions

1-hour personalized coaching

Real Projects

Build portfolio applications

Best Practices

Industry-standard techniques

Career Support

Interview prep & job guidance

Total Investment
$200
Duration
30 hours
1h/day

Enrollment Closes In

Days
Hours
Minutes
Seconds
Spots Available 5 of 10 remaining
Next cohort starts:
June 11, 2025

Join the Program

Complete your application to secure your spot

Application Submitted!

Thank you for your interest in our Laravel mentorship program. We'll contact you within 24 hours with next steps.

What happens next?

  • Confirmation email with program details
  • WhatsApp message from our team
  • Onboarding call to discuss your goals

Tags

Comments

No comments yet. Be the first to comment!

Please log in to post a comment:

Sign in with Google

Related Posts

Laravel 12 Multi-Auth System: Implementing Separate Admin and User Tables
Kritim Yantra Kritim Yantra
Feb 28, 2025
Laravel 12 Roles and Permissions Setup: Complete Guide
Kritim Yantra Kritim Yantra
Feb 28, 2025
Laravel 12 & AdminLTE Integration: Setup Your Stunning Admin Dashboard
Kritim Yantra Kritim Yantra
Feb 28, 2025