Kirsten
Kirsten

Reputation: 31

jQuery Stop validation on cancel ui dialog

I have several forms with separate validators defined. These all work fine and validates as expected. However if I click the cancel button in the dialog box it still validates the form and shows errors. I have to click the cancel button twice for the form to close. If I click the [x] to close the dialog I briefly see the error message but the form closes. I can live with that.

This is my code:

var renewValidator = $("#FormRenew").validate({
  rules: {
    NewNo: {
      remote: {
        url: "action.php?checkDup=1"
      }
    }
  }
});

$("#dialog").dialog({
  bgiframe: true,
  autoOpen: false,
  width: 450,
  modal: true,
  buttons: {
    'Renew': function() {
      if (renewValidator.valid()) {
        $.ajax({
          type: "POST",
          url: "ajax.php",
          data: queryString,
          success: function(msg) {...
                                 }
                                 });
          $(this).dialog('close');
        }
               },
               Cancel: {
               text: 'Cancel',
               immediate: "true",
               formnovalidate: 'formnovalidate',
               class: 'cancel',
               click: function(e) {
          console.log('Cancel clicked!');
          e.preventDefault();
          $("form").validate().cancelSubmit = true;
          $(this).dialog('close');
        }
      }
    },
    beforeClose: function() {
      renewValidator.resetForm();
      $("#FormRenew").trigger("reset");
    }
  });

Initially I just had a simple cancel like this Cancel:

function() {
    $(this).dialog('close');
}

But I added the various options as suggested in other posts. None works for me.

Upvotes: 0

Views: 1205

Answers (1)

Sparky
Sparky

Reputation: 98718

The buttons have absolutely nothing to do with this. Validation is triggered when you focus out of the field. Since the modal opens with the field in focus, simply clicking anywhere on the page causes a focusout event to fire and therefore triggers validation.

  1. Setting the onfocusout option to false within .validate() is part of the solution. However, as explained in my comments, you cannot trigger validation at all with any button because they are outside the form tags (and not type="submit").

  2. Change your renewValidator.valid() into $("form").valid() so validation can be programmatically triggered when Renew is clicked.

IMPORTANT: Since your buttons are outside the <form>, you can also remove all that special "button canceling" code. A button cannot submit or trigger validation when it's outside the form container or when it's type="button".

DEMO: jsfiddle.net/yggg588c/

Upvotes: 1

Related Questions