How Do I Validate a Form Before Submitting Using Ajax

admin_img Posted By Bajarangi soft , Posted On 10-02-2021

Data submitted in a form is usually validated in some way. And if there is any unacceptable data, the form is traditionally re-displayed, together with validation messages. In such a case, it is important to immediately inform screen reader users, so they know that they have to look at their data and submit again.

How Do I Validate a Form Before Submitting Using Ajax

Step 1: Add Route
routes/web.php

Route::get('my-form','HomeController@myform');

Route::post('my-form','HomeController@myformPost')->name('my.form');

Step 2: Create Controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Validator;

class HomeController extends Controller

{

 

/**

* Display a listing of the myform.

*

* @return \Illuminate\Http\Response

*/

public function myform()

{

return view('myform');

}

 

/**

* Display a listing of the myformPost.

*

* @return \Illuminate\Http\Response

*/

public function myformPost(Request $request)

{

 

$validator = Validator::make($request->all(), [

'first_name' => 'required',

'last_name' => 'required',

'email' => 'required|email',

'address' => 'required',

]);

 

if ($validator->passes()) {

return response()->json(['success'=>'Added new records.']);

}

 

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

}

 


Step3: Script of Validation For Form Using Ajax
<script>
    if ($("#post-form").length > 0) {
        $("#post-form").validate({

            rules: {
                name: {
                    required: true,
                    maxlength: 50
                },
                email: {
                    required: true,
                    maxlength: 250
                } ,
                password: {
                    required: true,
                    maxlength: 250
                }
            },
            messages: {
                name: {
                    required: "Please Enter Name",
                    maxlength: "Your last name maxlength should be 50 characters long."
                },
                email: {
                    required: "Please Enter Body",
                    maxlength: "Your last body maxlength should be 250 characters long."
                },
                password: {
                    required: "Please Enter Body",
                    maxlength: "Your last body maxlength should be 250 characters long."
                },
            },
            submitHandler: function (form) {
                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });
                $('#send_form').html('Sending..');
                $.ajax({
                    url: '/save-form',
                    type: "POST",
                    data: $('#post-form').serialize(),
                    success: function (response) {
                        $('#send_form').html('Submit');
                        $('#res_message').show();
                        $('#res_message').html(response.msg);
                        $('#msg_div').removeClass('d-none');

                        document.getElementById("post-form").reset();
                        setTimeout(function () {
                            $('#res_message').hide();
                            $('#msg_div').hide();
                        }, 10000);
                    }
                });
            }
        })
    }
</script>
Step:4 Create a blade view
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css"/>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/additional-methods.min.js"></script>
    <style>
        .error {
            color: red;
        }
    </style>
</head>
<body>
<div class="container">

    <form id="post-form" method="post" action="javascript:void(0)">
        @csrf

        <div class="col-md-12">
            <div class="alert alert-success d-none" id="msg_div">
                <span id="res_message"></span>
            </div>
        </div>


        <div class="col-md-12">
            <div class="form-group">
                <label>Name<span class="text-danger">*</span></label>
                <input type="text" name="name" placeholder="Enter name" class="form-control">
                <span class="text-danger p-1">{{ $errors->first('name') }}</span>
            </div>
        </div>
        <div class="col-md-12">
            <div class="form-group">
                <label>Email<span class="text-danger">*</span></label>
                <input type="text" name="email" placeholder="Enter eamil" class="form-control">
                <span class="text-danger p-1">{{ $errors->first('email') }}</span>
            </div>
        </div>


        <div class="col-md-12">
            <div class="form-group">
                <label>Password<span class="text-danger">*</span></label>
                <input type="password" class="form-control" name="password" placeholder="Enter your password">
                <span class="text-danger">{{ $errors->first('Password') }}</span>
            </div>
        </div>


        <div class="col-md-12">
            <button type="submit" id="send_form" class="btn btn-block btn-success">Submit</button>
        </div>

    </form>

</div>


</body>
<script>
    if ($("#post-form").length > 0) {
        $("#post-form").validate({

            rules: {
                name: {
                    required: true,
                    maxlength: 50
                },
                email: {
                    required: true,
                    maxlength: 250
                } ,
                password: {
                    required: true,
                    maxlength: 250
                }
            },
            messages: {
                name: {
                    required: "Please Enter Name",
                    maxlength: "Your last name maxlength should be 50 characters long."
                },
                email: {
                    required: "Please Enter Body",
                    maxlength: "Your last body maxlength should be 250 characters long."
                },
                password: {
                    required: "Please Enter Body",
                    maxlength: "Your last body maxlength should be 250 characters long."
                },
            },
            submitHandler: function (form) {
                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });
                $('#send_form').html('Sending..');
                $.ajax({
                    url: '/save-form',
                    type: "POST",
                    data: $('#post-form').serialize(),
                    success: function (response) {
                        $('#send_form').html('Submit');
                        $('#res_message').show();
                        $('#res_message').html(response.msg);
                        $('#msg_div').removeClass('d-none');

                        document.getElementById("post-form").reset();
                        setTimeout(function () {
                            $('#res_message').hide();
                            $('#msg_div').hide();
                        }, 10000);
                    }
                });
            }
        })
    }
</script>
</html>

Related Post