[jquery] jQuery Form Validation before Ajax submit

JavaScript bit:

$(document).ready(function()
    {
            $('#form').submit(function(e)
            {     

                e.preventDefault();
                var $form = $(this);

                // check if the input is valid
                if(! $form.valid()) return false;
                    $.ajax(
                    {
                    type:'POST',
                    url:'add.php',
                    data:$('#form').serialize(),
                    success:function(response)
                    {
                        $("#answers").html(response);
                    }
                });     

            })
    });

HTML bit:

    <input type="text" name="answer[1]" class="required" />
    <input type="text" name="answer[2]" class="required" />

So this is the code I am trying to use. The idea is to get all my inputs validated before I send my form with Ajax. I've tried numerous versions of this now but every time I end up with submitting even though the form is not entirely filled out. All my inputs are of the "required" class. Can anyone see what I am doing wrong?

Also, I depend on class-based requirements as my input names are generated with php so I can never be sure what name[id] or input types I get.

I show/hide questions as I go through it in "pages".

<input type="button" id="next" onClick="toggleVisibility('form3')" class="next-btn"/>

JS:

function toggleVisibility(newSection) 
        {
            $(".section").not("#" + newSection).hide();
            $("#" + newSection).show();
        } 

This question is related to jquery ajax jquery-validate validation

The answer is


I think that i first validate form and if validation will pass, than i would make ajax post. Dont forget to add "return false" at the end of the script.


You need to trigger form validation before checking if it is valid. Field validation runs after you enter data in each field. Form validation is triggered by the submit event but at the document level. So your event handler is being triggered before jquery validates the whole form. But fret not, there's a simple solution to all of this.

You should validate the form:

if ($(this).validate().form()) {
  // do ajax stuff
}

https://jqueryvalidation.org/Validator.form/#validator-form()


first you don't need to add the classRules explicitly since required is automatically detected by the jquery.validate plugin. so you can use this code :

  1. on form submit , you prevent the default behavior
  2. if the form is Invalid stop the execution.
  3. else if valid send the ajax request.
$('#form').submit(function (e) {
  e.preventDefault();
  var $form = $(this);

  // check if the input is valid using a 'valid' property
  if (!$form.valid) return false;

  $.ajax({
    type: 'POST',
    url: 'add.php',
    data: $('#form').serialize(),
    success: function (response) {
      $('#answers').html(response);
    },
  });
});

You can try doing:

if($("#form").validate()) {
 return true;
} else {
 return false;
}

function validateForm()
{
    var a=document.forms["Form"]["firstname"].value;
    var b=document.forms["Form"]["midname"].value;
    var c=document.forms["Form"]["lastname"].value;
    var d=document.forms["Form"]["tribe"].value;
    if (a==null || a=="",b==null || b=="",c==null || c=="",d==null || d=="")
    {
        alert("Please Fill All Required Field");
        return false;
    }
    else{

        $.ajax({
        type: 'post',
        url: 'add.php',
        data: $('form').serialize(),
        success: function () {
          alert('Patient added');
          document.getElementById("form").reset();
        }
      });

    }
}

  $(function () {

    $('form').on('submit', function (e) {
      e.preventDefault();

      validateForm();


    });
  });

This specific example will just check for inputs but you could tweak it however, Add something like this to your .ajax function:

beforeSend: function() {                    
    $empty = $('form#yourForm').find("input").filter(function() {
        return this.value === "";
    });
    if($empty.length) {
        alert('You must fill out all fields in order to submit a change');
        return false;
    }else{
        return true;
    };
},

I think submitHandler with jquery validation is good solution. Please get idea from this code. Inspired from @Darin Dimitrov

$('.calculate').validate({

                submitHandler: function(form) {
                    $.ajax({
                        url: 'response.php',
                        type: 'POST',
                        data: $(form).serialize(),
                        success: function(response) {
                            $('#'+form.id+' .ht-response-data').html(response);
                        }            
                    });
                }
            });

> Required JS for jquery form validation
> ## jquery-1.7.1.min.js ##
> ## jquery.validate.min.js ##
> ## jquery.form.js ##

$("form#data").validate({
    rules: {
        first: {
                required: true,
            },
        middle: {
            required: true,
        },          
        image: {
            required: true,
        },
    },
    messages: {
        first: {
                required: "Please enter first",
            },
        middle: {
            required: "Please enter middle",
        },          
        image: {
            required: "Please Select logo",
        },
    },
    submitHandler: function(form) {
        var formData = new FormData($("#image")[0]);
        $(form).ajaxSubmit({
            url:"action.php",
            type:"post",
            success: function(data,status){
              alert(data);
            }
        });
    }
});

Form native JavaScript checkValidity function is more then enough to trigger the HTML5 validation

$(document).ready(function() {
    $('#urlSubmit').click(function() {
        if($('#urlForm')[0].checkValidity()) {
            alert("form submitting");
        }
    });
});

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to jquery-validate

Phone Number Validation MVC Jquery Validate custom error message location Jquery validation plugin - TypeError: $(...).validate is not a function JQuery Validate input file type jquery to validate phone number Bootstrap with jQuery Validation Plugin jQuery Validation plugin: validate check box jQuery select box validation Confirm Password with jQuery Validate MVC 4 client side validation not working

Examples related to validation

Rails 2.3.4 Persisting Model on Validation Failure Input type number "only numeric value" validation How can I manually set an Angular form field as invalid? Laravel Password & Password_Confirmation Validation Reactjs - Form input validation Get all validation errors from Angular 2 FormGroup Min / Max Validator in Angular 2 Final How to validate white spaces/empty spaces? [Angular 2] How to Validate on Max File Size in Laravel? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery