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

Comments

Kris van Waterschoot (24 Aug 2009)

Can you please post all the necessary code to make this example work? I'm not able to have successful validation in a jquery ui dialog.

Thanks,
Kris

Adam Schroeder (29 Dec 2009)

I don't think this method works when you have a remote validation rule. For some reason, the remote validation request doesn't get returned until AFTER the call to

$("#form").validate().form()

Adam Schroeder (29 Dec 2009)

It appears the problem I described above is not local to this situation, but is in fact a problem with remote validation in general.

It has to do with the fact that the current remote validation is asynchronous.

A bugfix is documented here:
http://old.nabble.com/%28validation%2...

Wordpress Design (09 Feb 2010)

Great guidelines. Thanks!

vanzari auto (23 Feb 2010)

It is interesting. I hope i can put this cod in my aplication.

make money online (24 Feb 2010)

thanks for all the great data i love it

writing 4 students (27 Feb 2010)

I like this article.

Add your comment

No HTML. Line breaks and URLs will automatically be converted.

(private)