Laravel 9 ajax form validation and display error messages

Laravel 9 ajax form validation and display error messages

Why validation required ?

Validation is required when we store or update data from our application to database. It helps us to understand the data format is ok or not, prevent to store data if any validation fails, check form input field is empty or not etc.

 

Laravel default validation system is cool and supper easy to apply in any application. But today's tutorial we will use the default validation with jquery and ajax also learn how to show error messag if the validation fails. While validation rule is used for any input fields we know that, server checks the input fields against define validation , and if any kind of validation fails it will redirect to create page with error messages.

 

 

We will do the bellow steps to complete the validation process.

 

1. Setup laravel project

2. Routes

3. Blade file inside views

4. Controller

5. Test validation and display error message

 

 

 

 

Step-1. Setup laravel project


 

We can setup a laravel project several ways. But there are two popular way for install a project, one is via composer and other is laravel installer. Make sure before install a laravel project you have install composer. If you wish to setup a new project using laravel installer in that case you also need to install laravel installer in your machine.

 

 

  How to install laravel installer globally ?

 

Open your terminal and run the bellow command.

composer global require laravel/installer

 

Setup Project

//BY laravel installer 
laravel new laravel-ajax-validation

//By composer
composer create-project laravel/laravel laravel-ajax-validation

 

 

 

Step- 2. Routes

 

In step 2 we will create two routes one is for return form page and another one is for submit our form.

 

 routes\web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AjaxValidationController;


Route::get('/',[AjaxValidationController::class,'welcome'])->name('welcome');
Route::post('/ajax-form-validate',[AjaxValidationController::class,'ajax_form_validate'])->name('ajax.form.validate');

From first route we will return welcome.blade.php file and next submit the form using the second route.

 

 

 

Step-3. Blade file inside views

 

At first let's design our form with the bellow code

 

welcome.blade.php

<form>
    @csrf
    <div class="row">
        <div class="col-md-12">
            <div class="mb-3">
                <label class="mb-1">{{ __('Your Name') }}</label>
                <input type="text" name="name" class="form-control" value="{{ old('name') }}">
            </div>
            <div class="mb-3">
                <label class="mb-1">{{ __('Your Email') }}</label>
                <input type="email" name="email" class="form-control" value="{{ old('email') }}">
            </div>
        </div>
        <button type="submit" class="btn btn-primary add-data">{{ __('Submit') }}</button>
    </div>
</form>

 

Now we will write our required jquery and ajax code

welcome.blade.php

<script>
    $(document).ready(function(){
        //add product
        $(document).on('click','.add-data',function(e){
            e.preventDefault();
            let name = $('#name').val();
            let email = $('#email').val();
            $.ajax({
                method:'post',
                url:'{{ route('ajax.form.validate') }}',
                data:{name:name,email:email},
                success:function(res){
                    //
                },
                error:function(err){
                    let error = err.responseJSON;
                    $.each(error.errors, function (index, value) {
                        $('.errorMsgntainer').append('<span class="text-danger">'+value+'<span>'+'<br>');
                    });
                }
            });
        })
    })
</script>

 

Let's see the full code in welcome.blade.php

resources\views\welcome.blade.php

<!doctype html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <title>{{ __('Laravel 9 ajax form validation') }}</title>
</head>
<body>
<div class="container">
    <div class="row mt-3">
        <div class="col-md-8 offset-md-2">
            <div class="card">
                <div class="card-header">
                    <div class="title">
                        <h3 class="text-left">{{ __('Laravel 9 ajax form validation.') }}</h3>
                    </div>
                </div>
                <div class="card-body">

                    <div class="errorMsgntainer"></div>

                    <form>
                        @csrf
                        <div class="row">
                            <div class="col-md-12">
                                <div class="mb-3">
                                    <label class="mb-1">{{ __('Your Name') }}</label>
                                    <input type="text" name="name" class="form-control" value="{{ old('name') }}">
                                </div>
                                <div class="mb-3">
                                    <label class="mb-1">{{ __('Your Email') }}</label>
                                    <input type="email" name="email" class="form-control" value="{{ old('email') }}">
                                </div>
                            </div>
                            <button type="submit" class="btn btn-primary add-data">{{ __('Submit') }}</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src ="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
</script>
<script>
    $(document).ready(function(){
        //add product
        $(document).on('click','.add-data',function(e){
            e.preventDefault();
            let name = $('#name').val();
            let email = $('#email').val();
            $.ajax({
                method:'post',
                url:'{{ route('ajax.form.validate') }}',
                data:{name:name,email:email},
                success:function(res){
                    //
                },
                error:function(err){
                    let error = err.responseJSON;
                    $.each(error.errors, function (index, value) {
                        $('.errorMsgntainer').append('<span class="text-danger">'+value+'<span>'+'<br>');
                    });
                }
            });
        })
    })
</script>
</body>
</html>

 

 

 

Step-4. Controller

 

Type the following command to create controller

php artisan make:controller AjaxValidationController

 

Once the controller created successfully we will return welcome.blade.php file first from controller

 public function welcome()
    {
        return view('welcome');
    }

 

Now we will validate our form using the laravel validation rules in controlller

public function ajax_form_validate(Request $request)
    {
        $request->validate([
            'name'=>'required|regex:/^[\pL\s\-]+$/u|max:50',
            'email'=>'required|regex:/(.+)@(.+)\.(.+)/i|email|max:50',
        ]);
     }

 

Let's see the complete code in controller

AjaxValidationController.php

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class AjaxValidationController extends Controller
{
    public function welcome()
    {
        return view('welcome');
    }


    public function ajax_form_validate(Request $request)
    {
        $request->validate([
            'name'=>'required|regex:/^[\pL\s\-]+$/u|max:50',
            'email'=>'required|regex:/(.+)@(.+)\.(.+)/i|email|max:50',
        ]);
     }
}

 

 

 

Step-5. Test validation and display error message

 

Before submit the form don't forget run the development server using the following command.

php artisan serve

 

If you submit the form and keep all input fields blank then display error messages like bellow image

display validation error message

 

 

 

 

 

 

 

 

 

 

 

 
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Thanks, hope this article helps you a lot.

 

 

 

 

 

 

If you like what you are reading, please consider buying us a coffee as a token of appreciation.

Buy Me A Coffee

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your ongoing support 

 

Tags

  • Share This:

Comments - 1

rownak jahan

Nice. Thanks a lot

Mar 11, 2023