Laravel 11 Client Side Form Validation using jQuery

Hello, Laravel web developers! In this article, we'll explore how to implement client-side form validation using jQuery in Laravel 11. We'll use validate.js to handle the form validation. With client-side validation, there's no need to submit the form and wait for the server to return validation errors.

Instead, validation errors are triggered instantly without a page refresh, and the error messages are displayed directly in the input fields.

Laravel 11 Client Side Form Validation using jQuery

Laravel 11 Client Side Form Validation using jQuery

 

Step 1: Install the Laravel 11 application

In this step, we'll install the laravel 11 application using the following command.

composer create-project laravel/laravel example-app

 

Step 2: Create Controller

Next, we'll create a controller using the following command and add the following function to that file.

php artisan make:controller FormController

app/Http/Controllers/FormController.php

<?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('create');
    }
        
    /**
     * 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'
            ]);
    
        $validatedData['password'] = bcrypt($validatedData['password']);
        $user = User::create($validatedData);
          
        return back()->with('success', 'User created successfully.');
    }
}

 

Step 3: Define Routes

Now, define the routes into the web.php file.

routes/web.php

<?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 4: Create Blade File

Next, create a blade file and add the following HTML code to that file.

resources/views/create.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 11 Client Side Form Validation using jQuery - Techsolutionstuff</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/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" />

    <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js"></script>

    <style>
        label.error {
            color: #dc3545;
            font-size: 14px;
        }
    </style>
</head>
<body>
<div class="container">

    <div class="card mt-5">
        <h3 class="card-header p-3"><i class="fa fa-star"></i> Laravel 11 Client Side Form Validation using jQuery - Techsolutionstuff</h3>
        <div class="card-body">
            
            @session('success')
                <div class="alert alert-success" role="alert"> 
                    {{ $value }}
                </div>
            @endsession
        
            @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') }}" id="regForm">
          
                {{ csrf_field() }}
          
                <div class="mb-3">
                    <label class="form-label" for="inputName">Name:</label>
                    <input 
                        type="text" 
                        name="name" 
                        id="inputName"
                        class="form-control" 
                        placeholder="Name">
                </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">
                </div>
         
                <div class="mb-3">
                    <label class="form-label" for="password">Password:</label>
                    <input 
                        type="password" 
                        name="password" 
                        id="password"
                        class="form-control" 
                        placeholder="Password">
                </div>

                <div class="mb-3">
                    <label class="form-label" for="inputPassword">Confirm Password:</label>
                    <input 
                        type="password" 
                        name="confirm_password" 
                        id="inputPassword"
                        class="form-control" 
                        placeholder="Password">
                </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>

<script type="text/javascript">
    $(document).ready(function(){
        $("#regForm").validate({
                rules: {
                    name: {
                        required: true,
                        maxlength: 60,
                    },
                    email: {
                        required: true,
                        email: true,
                        maxlength: 50
                    },
                    password: {
                        required: true,
                        minlength: 5
                    },
                    confirm_password: {
                        required: true,
                        equalTo: "#password"
                    },
                },
                messages: {
                    name: {
                        required: "Name field is required",
                        maxlength: "Name field cannot be more than 20 characters"
                    },
                    email: {
                        required: "Email field is required",
                        email: "Email field must be a valid email address",
                        maxlength: "Email field cannot be more than 50 characters",
                    },
                    password: {
                        required: "Password field is required",
                        minlength: "Password field must be at least 5 characters"
                    },
                    confirm_password: {
                        required:  "Confirm field password is required",
                        equalTo: "Password field and confirm password field should same"
                    }
                }
            });
    });
</script>
</html>

 

Step 5: Run the Laravel 11 Application

Now, run the laravel 11 application using the following command.

php artisan serve

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS