Laravel 10 Form Validation Example

    In this article, we will see the laravel 10 form validation example. Here, we will learn about basic form input with laravel validation. Laravel provides several different approaches to validate your application's incoming data.

    For any incoming data, we need to validate it before storing it in the database. It is most common to use the validate method available on all incoming HTTP requests.

    So, let's see how to validate a form in laravel 10, form validation in laravel 10, laravel 10 validation, custom validation in laravel 10, and custom laravel validation message.

Step 1: Install Laravel 10

    In this step, we will install the laravel 10 application using the following command.

composer create-project laravel/laravel laravel_10_form_validation
Step 2: Add Route

    In this step, we will add routes to the web.php file.

    routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('index', [ UserController::class, 'index' ]);
Route::post('store', [ UserController::class, 'store' ])->name('store');
Read Also: Laravel 10 Composer-runtime-api ^2.2 Error - Fixed
Step 3: Create UserController

    Now, we will create UserController using the following command.

php artisan make:controller UserController

    app/Http/Controllers/UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller
{
    public function index(){
        return view('index');
    }

    public function store(Request $request){
        $validatedData = $request->validate([
            'name' => 'required',
            'password' => 'required|min:5',
            'confirm_password' => 'required|same:password|min:5',
            'email' => 'required|email|unique:users'
        ], [
            'name.required' => 'Name field is required.',
            'password.required' => 'Password field is required.',
            'confirm_password.required' => 'Confirm 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.');
    }
}

    In laravel 10 Alternatively, validation rules may be specified as arrays of rules instead of a single | delimited string.

$validatedData = $request->validate([
    'name' => 'required',
    'password' => ['required', 'min:8'],
    'email' => ['required, email, unique:users'],
]);
Read Also: Multi Step Form Wizard jQuery Validation
Stopping On First Validation Failure

    Sometimes we need to stop running validation rules on an attribute after the first validation failure. To do so, assign the bail rule to the attribute in laravel 10.

$request->validate([
    'name' => 'bail|required|unique:users|max:255',
    'password' => ['required', 'min:8'],
    'email' => ['bail, required, email, unique:users'],
]);

    In this example, if the unique rule on the name attribute fails, the max rule will not be checked. Rules will be validated in the order they are assigned. 

Step 4: Add Blade File

    In this step, we will create an index.blade.php file.

    resources/views/index.blade.php

<!DOCTYPE html>
<html>
    <head>
        <title>Laravel 10 Form Validation Example - Websolutionstuff</title>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
        <div class="container col-md-6">    
            <h3 class="mt-5">Laravel 10 Form Validation Example - Websolutionstuff</h3>       
            @if(Session::has('success'))
            <div class="alert alert-success">
                {{ Session::get('success') }}
                @php
                    Session::forget('success');
                @endphp
            </div>
            @endif
        
            <!-- Way 1: Display All Error Messages -->
            @if ($errors->any())
                <div class="alert alert-danger">                
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif
        
            <form method="POST" action="{{ route('store') }}">      
                {{ csrf_field() }}      
                <div class="mb-3">
                    <label class="form-label" for="inputName">Name:</label>
                    <input type="text" name="name" 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="inputEmail">Email:</label>
                    <input type="text" name="email" class="form-control @error('email') is-invalid @enderror" placeholder="Email">
    
                    @error('email')
                        <span class="text-danger">{{ $message }}</span>
                    @endif
                </div>
        
                <div class="mb-3">
                    <label class="form-label" for="inputPassword">Password:</label>
                    <input type="password" name="password" 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="inputPassword">Confirm Password:</label>
                    <input type="password" name="confirm_password" class="form-control @error('confirm_password') is-invalid @enderror" placeholder="Confirm Password">
    
                    <!-- Way 3: Display Error Message -->
                    @if ($errors->has('confirm_password'))
                        <span class="text-danger">{{ $errors->first('confirm_password') }}</span>
                    @endif
                </div>
        
                <div class="mb-3">
                    <button class="btn btn-success btn-submit">Submit</button>
                </div>
            </form>
        </div>
    </body>
</html>
Read Also: Laravel 9 Form Collective Example

    Output:

    laravel_10_form_validation_example_output

    You might also like:

Bình luận
Vui lòng đăng nhập để bình luận
Một số bài viết liên quan