JQuery Ajax Form Validation in Laravel 8 Tutorial

Share this Article
Reading Time: 5 minutes
7,120 Views

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.


Laravel Installation

We will create laravel project using composer. So, please make sure your system should have composer installed. If not, may be this article will help you to Install composer in system.

Here is the command to create a laravel project-

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

To start the development server of Laravel –

$ php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your 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.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5