ajax form validation in laravel 5

I am new in laravel and need help.

These are the values I'm getting via ajax, all values are to be stored in db, but how do I validate[check] if there are existing values or not before submitting a form using ajax?

$("#submit").click(function(e){  
        e.preventDefault();
        var url = "{!! URL::to('/') !!}";
        var id="{!! @$department->id !!}";
        var token = "{!! csrf_token() !!}";
        var customer_id = $("#customer_id").val();
        var visiting_address1 = $("#visiting_address1").val();
            var department_id = $("#department_id").val();  

        // AJAX Code To Submit Form.
        $.ajax({
            type: "POST",
            url: url+"/customer/"+customer_id+"/popup_store",  
            data: { '_token':token, 'rest':'true', 'customer_id':$("#customer_id").val(), 'main_address':$("#main_address").val(),'visiting_city':$("#visiting_city").val(),'visiting_address':$("#visiting_address1").val(),'visiting_zip':$("#visiting_zip").val()},
            async : false,
            success : function(data) { 
            if(data == "success")
            {
                $("#addrecords").modal('hide');

            }
            else 
                alert(data);
            }
        });

    }); 

Answers 1

  • First of all define you Jquery validation for you form like this:

    $("#myForm").validate({
        // Specify the validation rules
        rules: {
            name: "required",
        },
        // Specify the validation error messages
        messages: {
            name: "Please enter name",
        },
        submitHandler: function (form) {
            // leave it blank here.
        }
    });
    

    And then in your click button of submit button, write if condition to check validations:

    $("#submit").click(function (e) {
        if ($('#myForm').valid()) {
            // your Ajax Call Code
        } else {
            return false;
        }
    });
    

Related Articles