Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Laravel 11 Custom Validation Error Message Tutorial

Last Updated on July 1, 2024 by

Laravel 11 has built-in validate() method, you can easily customize validation rules and error messages in it.

Let’s start creating custom validation error rules and messages in the application for the form:

Step 1: Define Routes

Edit routes/web.php file, and define routes in it to handle form requests:

<?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 Controller

Run the following command to create a controller:

php artisan make:controller FormController

Edit app/http/controllers/FormController.php file, and create some methods in it to display form and validate 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 application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(): View
    {
        return view('my_form');
    }
          
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request): RedirectResponse
    {
        $validatedData = $request->validate([
                'name' => 'required',
                'password' => 'required|min:5',
                'email' => 'required|email|unique:users'
            ], [
                'name.required' => 'Name field is required.',
                'password.required' => 'Password field is required.',
                'email.required' => 'Email field is required.',
                'email.email' => 'Email field must be email address.'
            ]);
        
        $validatedData['password'] = bcrypt($validatedData['password']);
        $user = User::create($validatedData);
              
        return back()->with('success', 'User created successfully.');
    }
}

Step 3 – Create Form View

Go to resources/views directory and create a my_form.blade.php file in it with html form:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 11 Custom Form Validation Tutorial - ItcodStuff.com</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/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 Tutorial - ItcodStuff.com</h3>
        <div class="card-body">
            @session('success')
                <div class="alert alert-success" role="alert"> 
                    {{ $value }}
                </div>
            @endsession
          
            <!-- Way 1: Display All Error Messages -->
            @if ($errors->any())
                <div class="alert alert-danger">
                    <strong>Whoops!</strong> There were some problems with your input.<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">
      
                    <!-- Way 2: Display 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">
      
                    <!-- Way 3: Display 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 – Test This Application

Run the following command to start application server:

php artisan serve

Open browser and type url http://localhost:8000/users/create in it to test this application.

Leave a Comment