JQuery Ajax Form Validation in Laravel 8 Tutorial

Share this Article

In web application, form must have validation rules. Validation rules can be from any end. Form validation using Client side library. Form validations handled by server side. Means we have several options to do this. The main reason is to protect input fields from invalid entries and restrict user.

Inside this article we will see the concept of ajax form validation in laravel 8. This will be very interesting to see and learn.

We will implement form validation using server side. Form data we will post via Ajax. In the request from client side, we will do request to server and validate form from server.

Let’s get started.


Installation of Laravel 8 Application

Laravel Installation can be done in two ways.

  • Laravel Installer
  • By using composer

Laravel Installer

To install Laravel via Laravel installer, we need to install it’s installer first. We need to make use of composer for that.

$ composer global require laravel/installer

This command will install laravel installer at system. This installation is at global scope, so you type command from any directory at terminal. To verify type the given command –

$ laravel

This command will open a command palette of Laravel Installer.

To create ad install laravel project in system,

$ laravel new blog

With the name of blog a laravel project will be created at your specified path.

By using composer

Alternatively, we can also install Laravel by Composer command create-project. If your system doesn’t has Composer Installed, Click here to Install Composer ? Here is the complete command to create a laravel project-

$ composer create-project --prefer-dist laravel/laravel blog

After following these steps we can install a Laravel 8 application into system. To start the development server of Laravel –

$ php artisan serve

This command outputs –

Starting Laravel development server: http://127.0.0.1:8000

Assuming laravel 8 already installed at system.


Create Routes

Open web.php from /routes folder and add these routes into it.

# Add this to header
use App\Http\Controllers\AjaxController;
use App\Http\Controllers\HomeController;

Route::get('add-form', [HomeController::class, 'addForm']);
Route::post('submit-form', [AjaxController::class, 'submitForm'])->name('add.form');

Create Controller

Open project into terminal and type these artisan command into it to create controllers.

$ php artisan make:controller HomeController

$ php artisan make:controller AjaxController

These commands will create HomeController.php and AjaxController.php files at /app/Http/Controllers folder.

HomeController will render form and AjaxController will process ajax request.

Open HomeController.php and write this code into it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    public function addForm()
    {
        return view('add-form');
    }
}

Open AjaxController.php and write this code into it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;

class AjaxController extends Controller
{
    public function submitForm(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'first_name' => 'required',
            'last_name' => 'required',
            'email' => 'required|email'
        ]);

        if ($validator->passes()) {
            return response()->json(['success' => 'Added new records.']);
        }

        return response()->json(['error' => $validator->errors()->all()]);
    }
}

Create Layout File with Ajax Code

Create a file with name add-form.blade.php at /resources/views folder. Open layout file and write this code into it.

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 8 Ajax Validation Tutorial - Online Web Tutor</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
</head>
<body>
       
<div class="container">
    <h3 style="text-align: center;">Laravel 8 Ajax Validation Tutorial - Online Web Tutor</h3>
       
    <div class="alert alert-danger print-error-msg" style="display:none">
        <ul></ul>
    </div>
       
    <form>

        {{ csrf_field() }}
        
        <div class="form-group">
            <label>First Name:</label>
            <input type="text" name="first_name" class="form-control" placeholder="First Name">
        </div>
       
        <div class="form-group">
            <label>Last Name:</label>
            <input type="text" name="last_name" class="form-control" placeholder="Last Name">
        </div>
       
        <div class="form-group">
            <strong>Email:</strong>
            <input type="text" name="email" class="form-control" placeholder="Email">
        </div>
       
        <div class="form-group">
            <button class="btn btn-success btn-submit">Submit</button>
        </div>
    </form>
</div>
       
<script type="text/javascript">
       
    $(document).ready(function() {

        $(".btn-submit").click(function(e){
          
            e.preventDefault();
       
            var _token = $("input[name='_token']").val();
            var first_name = $("input[name='first_name']").val();
            var last_name = $("input[name='last_name']").val();
            var email = $("input[name='email']").val();
       
            $.ajax({
                url: "{{ route('add.form') }}",
                type:'POST',
                data: {_token:_token, first_name:first_name, last_name:last_name, email:email},
                success: function(data) {
                    if($.isEmptyObject(data.error)){
                        alert(data.success);
                        $(".print-error-msg").css({
                            display:"none"
                        });
                    }else{
                        printErrorMsg(data.error);
                    }
                }
            });
       
        }); 
       
        function printErrorMsg (msg) {
            $(".print-error-msg").find("ul").html('');
            $(".print-error-msg").css('display','block');
            $.each( msg, function( key, value ) {
                $(".print-error-msg").find("ul").append('<li>'+value+'</li>');
            });
        }
    });


</script>


</body>
</html>

Application Testing

Open project to terminal and type the command to start development server

$ php artisan serve

URL – http://127.0.0.1:8000/add-form

We hope this article helped you to learn about jQuery Ajax Form Validation in Laravel 8 Tutorial in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Find More on Laravel 8 Articles here

Leave a Comment

What are CSRF Functions in CodeIgniter 4 Tutorial
MySQL Stored Procedure in CodeIgniter 4 Tutorial