Question

I'm using the ajaxform jQuery plugin to create ajaxed HTML forms and want to implement validation using the jQuery Validation plugin.

I'm not sure what is the best way to implement this.

It doesn't work out-of-the-box for me. I set up the form with form.ajaxform({}) and then set up validation with form.validate({}). The invalidHandler event fires on the validation plugin, but ajaxform still submits the form.

How do I wire the two up properly?


My code:

_initializeValidation: function (form) {

    var options = {
        rules:
            {
                Name:
                {
                    required: true
                }
            },
        messages:
            {
                Name: "Name is required",
                ShortName: "Short name is required"
            }
    };

    if (form.find("#ShortName").length == 1)
        $.extend(options.rules, { ShortName: { required: true} });

    form.validate(options);
}

/* 
*   Initializes a newly loaded edit form
*/
_initializeEdit: function (panel) {
    var thisDetailTab = this;
    var form = panel.find("form");
    form.ajaxForm(
        {
            target: panel,
            url: this._config.updateUrl,
            beforeSubmit: function (arr, $form, options) {
                return form.valid();
            },
            success: function (responseText, statusText, xhr, form) {
                thisDetailTab._initializeDetails(panel);
                thisDetailTab._config.refreshSummary();
            }
        }
    );

    this._initializeValidation(form);

    var cancelButton = panel.find(".cancelButton");
    cancelButton.click(function (event) {
        $.ajax(
            {
                url: thisDetailTab._config.detailsUrl,
                success: function (data) {
                    panel.empty();
                    panel.append(data);
                    thisDetailTab._initializeDetails(panel);
                }
            }
        );
    });
}
Was it helpful?

Solution

Instead of .ajaxForm(), use .ajaxSubmit() in your submitHandler (which only fires on success), like this:

$("form").validate({
  rules: { ... },
  submitHandler: function(form) {
    $(form).ajaxSubmit({ ...options... });
  }
});

This way it only attempts to do an AJAX submission if the validation is successful (otherwise the invalidHandler is fired). If you want to see a live example, here's the related validation plugin demo.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top