Using jQuery Validation with an Ajax Submitted jQuery UI Dialog

Quick tip.

Utilizing jQuery plugins in your project can greatly increase your productivity. However, it isn't always obvious how best to use them in unison.

Recently, I needed to combine the jQuery UI Dialog, jQuery Validation Plugin, and jQuery Ajax.

The jQuery Validation Plugin has a built in hook which allows you to assign a function that will trigger the validation event for a given form:

var v = jQuery("#form").validate({
	submitHandler: function(form) {
		jQuery(form).ajaxSubmit({
			target: "#result"
		});
	}
});

Unfortunately, this method won't work with the jQuery UI Dialog. The work around is to manually trigger the validation of the form from within the function that handles the dialog's "Ok" button:

$('#div').dialog({
    buttons: {
        "Ok": function() {                            
            var options = { 
                success: showResponse,
                url: '/submit/',
                type: 'post',
                dataType: 'json',
            }; 

            // Manually trigger validation
            if ($("#form").validate().form() == true) {
                $('#form').ajaxSubmit(options); 
            }
        }
    }
});

blog comments powered by Disqus