jQuery: how to include validation in the ajaxForm function?

Randy Tang picture Randy Tang · Mar 10, 2013 · Viewed 10.8k times · Source

This question has been asked, but the answer wasn't confirmed. I tried it but it didn't work. So I would like to ask the same question again (Is this appropriate? If not, please advise me what to do).

I have a form which needs to be validates and then submitted with ajaxForm (the form contains image and file data, so submission with .serialize() won't work). The following are the details:

HTML:

<form id="myForm" action="..." method="post" enctype="multipart/form-data">
  ...
  <input type="file" name="image" /><br />
  <input type="file" name="file" /><br />
  ...
</form>

jQuery:

$(document).ready(function() {

  $("#myForm").ajaxForm ({

    beforeSubmit: function() {
      $("#myForm").validate({
        onkeyup:false,
        rules: {
          ...
        },
        messages: {
          ...
        },
      });
    },

    success: function(returnData) {
      $('#content').html(returnData);
    }

  });

});

The ajaxForm part is OK. But the form is simply submitted without validation.

Answer

Sparky picture Sparky · Mar 10, 2013

.validate() is used for initializing the plugin on DOM ready, so pull that outside of the other function.

Initialize the two plugins within DOM ready, and then utilize any appropriate built-in callback functions...

You will not need to worry about creating any new submit handler or click handler functions since both plugins already capture the submit event automatically.

Working DEMO: http://jsfiddle.net/MF26D/

Rearrange your code into something more like this:

$(document).ready(function () {

    $("#myForm").validate({ // initialize the plugin
        // any other options,
        onkeyup: false,
        rules: {
            //...
        },
        messages: {
            //...
        }
    });

    $("#myForm").ajaxForm({ // initialize the plugin
        // any other options,
        beforeSubmit: function () {
            return $("#myForm").valid(); // TRUE when form is valid, FALSE will cancel submit
        },
        success: function (returnData) {
            $('#content').html(returnData);
        }
    });

});