jQuery Form Validation before Ajax submit

286,689

Solution 1

You could use the submitHandler option. Basically put the $.ajax call inside this handler, i.e. invert it with the validation setup logic.

$('#form').validate({

    ... your validation rules come here,

    submitHandler: function(form) {
        $.ajax({
            url: form.action,
            type: form.method,
            data: $(form).serialize(),
            success: function(response) {
                $('#answers').html(response);
            }            
        });
    }
});

The jQuery.validate plugin will invoke the submit handler if the validation has passed.

Solution 2

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);
    },
  });
});

Solution 3

You can try doing:

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

Solution 4

> 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);
            }
        });
    }
});

Solution 5

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;
    };
},
Share:
286,689
Tom
Author by

Tom

Updated on July 09, 2022

Comments

  • Tom
    Tom almost 2 years

    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();
            } 
    
  • Tom
    Tom almost 12 years
    But I can still serialize #answers before I validate or stick it right before $.ajax ?
  • Darin Dimitrov
    Darin Dimitrov almost 12 years
    #answers is your result div. If you want to send the form input field values along with the AJAX request, use the .serialize() method, exactly as shown in my answer: data: $(form).serialize() => inside the submit handler.
  • Tom
    Tom almost 12 years
    I do change display: none on my form as I go dividing it up into several "pages". Think that could cause some problems?
  • amd
    amd almost 12 years
    check if there an error in your browser log, what browser you use ?
  • Tom
    Tom almost 12 years
    I am using Google Chrome, but I can't find any errors there. Gonna try with this code once more.
  • Tom
    Tom almost 12 years
    Won't submit at all now, this goes into the $(document).ready(function(){ right?
  • amd
    amd almost 12 years
    yes it should be in the document ready block, have you added an ID to your form ?, your form must have <form id='form'>... <input type=submit value=submit></form>
  • Tom
    Tom almost 12 years
    Now I am getting somewhere. I only had a input type="button". Still it only requires my checkboxes. It ignores the textboxes and radiobuttons. Could it be because they are hidden? I hide older questions and only present the current "page"
  • Tom
    Tom almost 12 years
    Seems it cannot operate over more than 1 "page". Added a textbox at the last "page" which it did require. Wonder if there is any way around this O_o
  • Tom
    Tom almost 12 years
    Also it changed it's method to get somehow, no idea why O_o
  • Tom
    Tom almost 12 years
    Do you think there's any chance that splitting up the form in several divs that are hidden/shown as the user goes through the form could have anything to do with me not getting this code to work?
  • Suhail Mumtaz Awan
    Suhail Mumtaz Awan over 8 years
    Right on target as always, +1
  • Zkk
    Zkk about 8 years
    Right on target² hahah +1
  • Deepa MG
    Deepa MG over 6 years
    This answer is quite clearly explained for beginers... Thanks! But is this also validate the file attachment !! How !!
  • luis
    luis about 6 years
    did it like this
  • Tim Diekmann
    Tim Diekmann about 6 years
    Welcome to Stack Overflow! Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.
  • Eugen Konkov
    Eugen Konkov about 6 years
    May you please extend you answer and shed the light on .ajaxSubmit. When I use it instead of $.ajax the common submit occur. How to prevent that?
  • Eugen Konkov
    Eugen Konkov about 6 years
    Does jquery.form.js required?
  • Eugen Konkov
    Eugen Konkov about 6 years
    may you please extend your answer with .ajaxSubmit?
  • Mujtaba
    Mujtaba about 3 years
    why to use comparison operators? can't we use form.valid() ?? that would be more efficient.