Skip to content

Laravel 12 Client-Side Form Validation Using jQuery

Learn how to implement client-side form validation in Laravel 12 using jQuery with a step-by-step example. Improve user experience and validate forms instantly.

Dasun Kalupahana Updated 2 min read 701 views 0 comments
On this page
  1. Why Use Client-Side Validation?
  2. Steps for Laravel 12 jQuery Client-Side Validation
  3. Final Thoughts

When building web applications with Laravel 12, form validation is a critical part of ensuring data integrity. While server-side validation is always a must (to protect your backend), sometimes adding client-side validation improves user experience.

With client-side validation, users get instant feedback before the form is even submitted, which saves time and reduces unnecessary server requests.

In this article, I’ll walk you through how to implement jQuery client-side form validation in a Laravel 12 project with a practical user registration form.

Why Use Client-Side Validation?

  • Provides instant feedback to users without reloading the page.
  • Reduces unnecessary form submissions.
  • Improves user experience while still keeping server-side validation as a backup.

Steps for Laravel 12 jQuery Client-Side Validation

We will create a simple registration form with Name, Email, Password, and Confirm Password fields. Then, we’ll apply jQuery validation rules.

Step 1: Install Laravel 12

If you don’t have a Laravel app yet, create one using Composer:

composer create-project laravel/laravel test-app

Step 2: Create a Form Request and Define Backend Validation

Run the following Artisan command:

php artisan make:request StoreUserRequest

This will create a new file inside app/Http/Requests/StoreUserRequest.php.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreUserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        return [
            'name' => 'required|string|max:60',
            'email' => 'required|email|unique:users,email|max:50',
            'password' => 'required|min:5',
        ];
    }
}

Step 3: Create Controller

Next, generate a new controller called UserController:

php artisan make:controller UserController

Now, open app/Http/Controllers/UserController.php and add the following code:

<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreUserRequest;
use App\Models\User;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;

class FormController extends Controller
{
    public function create(): View
    {
        return view('users.create-user');
    }

    public function store(StoreUserRequest $request): RedirectResponse
    {
        try {
            $validatedData = $request->validated();

            $validatedData['password'] = bcrypt($validatedData['password']);
            User::create($validatedData);

            return back()->with('success', 'User created successfully.');
        } catch (Exception $exception) {
            // Log the error for debugging
            Log::error("User creation failed: {$exception->getMessage()}");

            return back()
                ->withInput()
                ->with('error', 'Something went wrong. Please try again.');
        }
    }
}

Step 4: Define Routes

Open routes/web.php and define routes for showing the form and handling submission:

Route::prefix('users')->group(function () {
    Route::get('create', [FormController::class, 'create']);
    Route::post('create', [FormController::class, 'store'])->name('users.store');
});

Step 5: Create Blade File

Now, create a Blade file resources/views/createUser.blade.php and add the form. We’ll also integrate jQuery and the jQuery Validation plugin.

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 12 Client Side Form Validation using jQuery</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.21.0/jquery.validate.min.js"></script>

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

    <div class="card mt-5">
        <h3 class="card-header p-3">User Registration Example</h3>
        <div class="card-body">

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

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

            <form method="POST" action="{{ route('users.store') }}" id="registrationForm">
                @csrf

                <div class="mb-2">
                    <label class="form-label">Name <span class="required">*</span></label>
                    <input type="text" name="name" class="form-control" placeholder="Enter Name">
                </div>

                <div class="mb-2">
                    <label class="form-label">Email <span class="required">*</span></label>
                    <input type="text" name="email" class="form-control" placeholder="Enter Email">
                </div>

                <div class="mb-2">
                    <label class="form-label">Password <span class="required">*</span></label>
                    <input type="password" name="password" id="password" class="form-control" placeholder="Enter Password">
                </div>

                <div class="mb-2">
                    <label class="form-label">Confirm Password <span class="required">*</span></label>
                    <input type="password" name="confirm_password" class="form-control" placeholder="Confirm Password">
                </div>

                <div class="mb-2">
                    <button class="btn btn-success">Submit</button>
                </div>
            </form>
        </div>
    </div>

</div>
</body>

<script>
$(document).ready(function(){
    $("#registrationForm").validate({
        rules: {
            name: {
                required: true,
                maxlength: 64
            },
            email: {
                required: true,
                email: true,
                maxlength: 64
            },
            password: {
                required: true,
                minlength: 8
            },
            confirm_password: {
                required: true,
                equalTo: "#password"
            }
        },
        messages: {
            name: {
                required: "Name is required",
                maxlength: "The name field may not be longer than 64 characters."
            },
            email: {
                required: "Email is required",
                email: "Enter a valid email address",
                maxlength: "The email field may not be longer than 64 characters."
            },
            password: {
                required: "Password is required",
                minlength: "Password must be at least 8characters"
            },
            confirm_password: {
                required: "Confirm Password is required",
                equalTo: "Passwords do not match"
            }
        }
    });
});
</script>
</html>

Step 6: Run Laravel Project

Finally, start your Laravel application:

php artisan serve

Open your browser and visit:

http://127.0.0.1:8000/users/create

You should now see the registration form with real-time jQuery validation in action.

Final Thoughts

By combining Laravel 12 server-side validation with jQuery client-side validation, you create a powerful and user-friendly form. This way, you protect your application from invalid data while also giving instant feedback to your users.

If you’re building forms frequently, you can extend this approach with custom validation rules, AJAX validation, or even integrate with libraries like Vue.js validation plugins.

If you found this helpful, feel free to share or drop a comment. Happy coding with Laravel!

Free resources for this topic

Code snippets and fixes for this topic

Get one practical tip every week

New tutorials, fixes and free cheat sheets from DEV Talk, straight to your inbox. No spam, unsubscribe in one click.

Free download: Laravel interview questions (PDF)

Have a question about this post?

Ask the community: other developers and the author can answer.

Ask the community

Get notified about new articles

One click, no email needed. Turn it off anytime with the bell at the top.

Get new articles on your iPhone

Add DEV Talk to your Home Screen, open it, then tap the bell.

Rate this post
0.0
Share

Enjoying the content?

If this article helped you, you can support the author with a coffee. It keeps new posts coming.

Buy me a coffee (opens in a new tab)

Comments 0

Be kind. Comments with links are reviewed before they appear.

No comments yet

Be the first to share your thoughts.

Get new articles in your inbox

Practical tutorials and deep dives, about once a week. No spam, unsubscribe anytime.

Privacy policy

Add DEV Talk to your Home Screen

  1. 1 Tap the Share button in Safari's toolbar.
  2. 2 Scroll down and tap Add to Home Screen.
  3. 3 Tap Add. Open it from the Home Screen to read like an app and to turn on notifications with the bell.

We use cookies to improve your experience and analyze traffic. By continuing, you agree to our Privacy Policy.