Laravel 11 Custom Validation Error Message Example | websolutioncode.com
Laravel 11 Custom Validation Error Message Example | websolutioncode.com

Laravel 11 Custom Validation Error Message Example

Laravel is a powerful PHP framework that simplifies web development. One of its many features is the built-in validation system, which makes it easy to ensure that the data your application receives is valid. Sometimes, the default error messages provided by Laravel may not be suitable for your application. In such cases, you might want to customize these messages to make them more user-friendly. This guide will show you how to create custom validation error messages in Laravel 11 with practical examples.

Setting Up Laravel

First, make sure you have Laravel installed. If you haven’t installed it yet, you can do so using Composer. Open your terminal and run:

composer create-project --prefer-dist laravel/laravel laravel-custom-validation

Navigate into your project directory:

cd laravel-custom-validation

Creating a Custom Validation Rule

Let’s start by creating a simple form to demonstrate custom validation. We’ll create a form that requires a username, email, and password. If the validation fails, we’ll display custom error messages.

Step 1: Create a Controller

First, let’s create a controller to handle the form submission. Run the following command:

php artisan make:controller UserController

Open the UserController.php file located in the app/Http/Controllers directory and add the following code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    public function create()
    {
        return view('user.create');
    }

    public function store(Request $request)
    {
        $customMessages = [
            'username.required' => 'The username field is required.',
            'email.required' => 'We need to know your email address!',
            'email.email' => 'The email address is not valid.',
            'password.required' => 'A password is required.',
            'password.min' => 'The password must be at least :min characters.',
        ];

        $request->validate([
            'username' => 'required',
            'email' => 'required|email',
            'password' => 'required|min:6',
        ], $customMessages);

        // If validation passes, do something, e.g., save to the database
        // User::create($request->all());

        return back()->with('success', 'Form submitted successfully.');
    }
}

Step 2: Create the Form View

Next, let’s create the form view. Create a new directory named user inside the resources/views directory. Then create a file named create.blade.php inside the user directory and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Custom Validation Example</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <h2>Create User</h2>

    @if ($errors->any())
        <div class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    @if (session('success'))
        <div class="alert alert-success">
            {{ session('success') }}
        </div>
    @endif

    <form action="{{ route('user.store') }}" method="POST">
        @csrf
        <div class="form-group">
            <label for="username">Username:</label>
            <input type="text" class="form-control" id="username" name="username">
        </div>
        <div class="form-group">
            <label for="email">Email:</label>
            <input type="email" class="form-control" id="email" name="email">
        </div>
        <div class="form-group">
            <label for="password">Password:</label>
            <input type="password" class="form-control" id="password" name="password">
        </div>
        <button type="submit" class="btn btn-primary">Submit</button>
    </form>
</div>
</body>
</html>

Step 3: Define Routes

Next, we need to define routes for displaying the form and handling the form submission. Open the routes/web.php file and add the following code:

use App\Http\Controllers\UserController;

Route::get('user/create', [UserController::class, 'create'])->name('user.create');
Route::post('user/store', [UserController::class, 'store'])->name('user.store');

Explanation

In this example, we have defined a form that asks for a username, email, and password. When the form is submitted, it sends a POST request to the store method of the UserController.

In the store method, we use the validate method to validate the request data. The second parameter of the validate method is an array of custom error messages. This array maps validation rules to custom messages.

Here is a breakdown of the custom messages:

  • 'username.required' => 'The username field is required.' specifies that if the username field is empty, the error message should be “The username field is required.”
  • 'email.required' => 'We need to know your email address!' specifies that if the email field is empty, the error message should be “We need to know your email address!”
  • 'email.email' => 'The email address is not valid.' specifies that if the email field does not contain a valid email address, the error message should be “The email address is not valid.”
  • 'password.required' => 'A password is required.' specifies that if the password field is empty, the error message should be “A password is required.”
  • 'password.min' => 'The password must be at least :min characters.' specifies that if the password field contains fewer than 6 characters, the error message should be “The password must be at least 6 characters.”

The :min placeholder in the password.min rule will be replaced with the actual minimum value specified in the validation rule.

Testing the Custom Validation Messages

To test the custom validation messages, start the Laravel development server:

php artisan serve

Visit http://localhost:8000/user/create in your browser. Fill out the form and submit it with invalid data to see the custom validation error messages.

For example, if you submit the form without filling out any fields, you will see the following custom error messages:

  • The username field is required.
  • We need to know your email address!
  • A password is required.

If you enter an invalid email address and a password with fewer than 6 characters, you will see the following messages:

  • The email address is not valid.
  • The password must be at least 6 characters.

Conclusion

Customizing validation error messages in Laravel 11 is straightforward. By specifying an array of custom messages, you can tailor the error messages to better suit your application’s needs and provide a better user experience. This example demonstrated how to create a simple form, validate the input, and display custom error messages when validation fails.