jQuery validation error inside the jQuery.UI.Dialog

This week I found a peculiar problem while trying to do validation inside a jQuery UI dialog box. Validation, although properly configured, would not happen, it would always show as valid.

This is the form, it is using the jquery.validation and the  jquery.ui.dialog components.

   1:  <form id="form1" runat="server">
   2:      <div id="dialog"></div>
   3:      <input type="button" id="load" value="Load Form" />
   4:  </form>
   5:  
   6:  <script type="text/javascript">
   7:  
   8:      $(function() {
   9:  
  10:          $('#form1').validate();
  11:  
  12:          $('#load').click(function() {
  13:              $.get('_form.aspx', function(data) {
  14:                  $('#dialog').html(data);
  15:                  $('#dialog').dialog();

  17:              });
  18:          });
  19:  
  20:      });
  21:  
  22:  
  23:  </script>

as you can see it is doing an ajax request to load the form. It then brings up the dialog box. Notice that the dialog div is inside the form therefore I’m expecting the loaded page to render within the form tag of the current page. This is the form that is loaded:

<input type="text" id="subject" class="required" />
<input type="submit" value="Submit Form" />

The problem is that the UI dialog will add a wrapper div and place it outside the form tag. It then moves the dialog div to be within it, effectively moving it outside the form. Therefore validation does not work as it is outside the form tag.

To fix this we write this simple line of code to reverse the process and move the dialog wrapper to be within the form tag.

$('#dialog').parent().appendTo($('#form1'));

It took me a little while to figure this out, and hopefully this will save you some time.

Cheers!


6 responses to this post.

  1. Posted by Julia on August 12, 2009 at 11:05 am

    Thank you very much!!!

    Reply

  2. Posted by Steve on August 19, 2009 at 12:11 pm

    Thank you for this. I can’t believe how much time I wasted trying to figure this out. I was able to narrow it down to possibly dropping the code out of the form field, but it took me a good couple of hours to get there.

    Reply

  3. Posted by sushil on October 13, 2009 at 3:34 am

    Mitch,

    where should be place this $(‘#dialog’).parent().appendTo($(‘#form1′)); line of code after the dialog opens or before opening the dialog..

    Reply

  4. Posted by Patrick Barnes on November 17, 2009 at 12:24 pm

    Place the code in the handler for the open event, which can be set in the dialog options, e.g.:

    ….
    open: function() {
    $(‘#dialog’).parent().appendTo($(‘#form1′));
    }

    or, if you use the dialogClass option you can drop “parent()”, e.g.:

    ….
    dialogClass: ‘myDialogClass’,
    open: function() {
    $(‘.myDialogClass’).appendTo($(‘#form1′));
    }

    Reply

Respond to this post