Validating a jQuery Dialog using jQuery Validate in ASP.Net

After I managed to create and display a jQuery dialog using the $().dialog() function, I wanted to replace my ad-hoc validation code with a “real” validation plugin, namely jQuery Validation. (naming consistency of jQuery plugins did not seem to matter until now, as there are several plugins with similar names in this area)

As much as I tried, the validator’s valid() would always return true, and debugging revealed that there were no elements to be checked, even though I had declared them in the validate() method.

Finally I came across this answer on SO, stating

the jQuery-UI dialog does not append to the form, it appends just before </body>, so the elements to validate are outside the <form></form> section

and suggesting the solution


Now it was obvious what’s happening: the dialog() function moves the <div> outside ASP.Net’s default form element (id=’aspnetForm’), directly under the <body> element.

Since I want to have several jQuery dialogs in my ASP.Net page, and cannot freely add <form> tags in the source code (especially not in .ascx and not in .aspx inside a MasterPage), I decided to create a <form> on the fly, and open the dialog inside the new form:

if (!$("#myForm").length) {
    .attr("id", "myForm")
    .attr("name", "myForm")

var d = $("#myDialog").dialog({ 
  autoOpen: false, 
  modal: true, 
  open: function () { 
    $("#myForm").validate({ ... }).resetForm(); 
  buttons: [ 
    { id: "OK", 
      click: function() { 
        if (!$("#myForm").valid()) 
          return false; 
        ... process data ... 


Note that I added the call to resetForm() to clear errors from a previous execution of the dialog.

You can call the form validation using the .valid() method and simply leave the dialog open if a validation error occurred.

Have a look at the demos for help regarding HTML and CSS declarations.


2 Responses to Validating a jQuery Dialog using jQuery Validate in ASP.Net

  1. […] jQuery Validation running, and now I know that it requires every input and select to have a name property; otherwise […]

  2. […] we want to support adding and editing records. Personally I prefer jQuery UI’s $.dialog() to open a form for editing the record, and upon closing the dialog, […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: