How to validate form using ajax in laravel? With Example

December 9, 2022
Laravel
How to validate form using ajax in laravel? With Example

In this post, you will learn how to validate the form input data using ajax in laravel.

Here are steps on how we will validate the input data:

  1. We will create the form in bootstrap 5
  2. Then in the jquery on button click we will send the form input data to the backend to get validated using laravel validator
  3. Then we will send the response back to the frontend.

Lets get Started!

I am assuming that you have installed the laravel in the folder, After that follow the steps below:

Step 1: Create From in Bootstrap 5

Create a new file in resources with the name of contact-us.blade.php and add the following Bootstrap code

<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">

    <meta name="csrf-token" content="{{csrf_token()}}" />

</head>

<body>



<!-- Footer End -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" referrerpolicy="no-referrer"></script>


<div class="container">
    <div class="content-section mt-5">
        <div class="row">
            <div class="col-lg-12">
                <h1 class="heading">
                    We would love hearing from you <br>
                    Get in Touch.
                </h1>
            </div>
        </div>

        <form class="main-form">
            <div class="row">
                <div class="col-lg-6">
                    <label class="form-label">First Name</label>
                    <input type="text" class="first_name form-control" placeholder="First Name">
                </div>
                <div class="col-lg-6">
                    <label class="form-label">Last Name</label>
                    <input type="text" class="last_name form-control" placeholder="Last Name">
                </div>
                <div class="col-lg-12">
                    <label class="form-label">Email</label>
                    <input type="text" class="email form-control" placeholder="Email">
                </div>

                <div class="col-lg-12">
                    <label class="form-label">Subject</label>
                    <input type="text" class="subject form-control" placeholder="Subject">
                </div>

                <div class="col-lg-12">
                    <label class="form-label">Message</label>
                    <textarea name="" id="" cols="30" rows="10" class="message form-control" placeholder="Message"></textarea>
                </div>

                <div class="col-lg-12">
                    <button type="button" class="btn btn-primary submit-button">Submit Information</button>
                </div>

                <div class="show-message">

                </div>

            </div>
        </form>
    </div>
</div>

<script>

    $('.submit-button').click(function (){


        let first_name=     $('.first_name').val();
        let last_name=      $('.last_name').val();
        let email=     $('.email').val();
        let subject=      $('.subject').val();
        let message=        $('.message').val();


        $('.show-message').empty();

        console.log('clicked');
        $.ajax({
            type : 'POST',
            url  : '{{route("contact-submit")}}',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            data: {
                first_name,
                last_name,
                email,
                subject,
                message,
            },
            success: function(data) {

                console.log('data',data);
                $('.show-message').html('Form Submitted');
            },

            error :  function(data,data2,data3)
            {

                let response=data.responseJSON;
                let all_errors=response.errors;

                console.log('all_errors',all_errors);

                $.each(all_errors,function(key,value){
                    $('.show-message').append(`<p>${value}</p>`);
                });


            }
        });
    });

</script>

</body>
</html>

This will create the contact form in the Bootstrap 5 which contains fields First Name , Last Name, Email, Subject and Message.

In the script part, on submit-button click, we are getting all the fields based on the class and then in ajax data field, we are adding all the fields.

We also have created show-message field in which we will show the status whether there is validation error or not.

Now in the case of success response 200, we are just showing message “Form Submitted”.

In the case of error with response 400, we are getting all the error message from the data.responseJSON and looping through the object itself. We will this in next step how these errors are generated.

We also added the csrf-token in ajax as the header which we were getting from the meta field csrf-token.

It will look like this

Boostrap 5 Contact Form

Step 2: Create Controller

Now we will create the controller ContactController in Controllers folder. Type the following command

php artisan make:controller ContactController

And the following code into the ContactController\

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Mail;

class ContactController extends Controller
{
    //
    public function index(Request  $request){

        $success=false;

        $validator=Validator::make($request->all(),[
            'first_name'=>'required',
            'last_name'=>'required',
            'email'=>'required|email',
            'subject'=>'required',
            'message'=>'required',
        ]);

        if($validator->fails())
        {
            return response()->json([
                'success'=>false,
                'errors'=>($validator->getMessageBag()->toArray()),
            ],400);
        }

        return response()->json([
            'success'=>true,
        ],200);

    }
}

In the above code, we are using Laravel Validator to validate the request, In the Validator array, we are mentioning that first_name, last_name, email, subject and message all are required and email field to be in email format.

If the request is failed it will go to the $validator->fails() part, in which were returning response with 400 response code and $validator->getMessageBag()->toArray() give us all the errors and convert them to object of array.

If the request doesn’t go to the $validator->fails() part, it means the request is valid, in that case we are sending response 200 back to the ajax.

Step 3: Create Routes

Now we need to create two routes, one for the loading the view itself and second for the ajax request itself.

Route::get('/', function () {
    return view('contact-us');
})->name('contact-us');

Route::post('/contact-submit',[\App\Http\Controllers\ContactController::class,'index'])->name('contact-submit');

In the above code, first we created route for the contact-us view and second route is for the submitting and validating the form.

Step 4: Run Application

Now you just need to run the application using the following command in the terminal:

php artisan serve

If you submit the empty form it will show you errors:

Bootstrap 5 Contact Form with Errors

But if you enter all fields it will show you “Form Submittted”

Bootstrap 5 Contact Form Submited

Conclusion:

Hope you have learned today how to validate input data using ajax in laravel in 4 easy steps.

See you in the next one.

Write a Reply or Comment

Your email address will not be published. Required fields are marked *


Icon