开发者

Does the Jquery validation plugin require a form tag?

开发者 https://www.devze.com 2022-12-18 03:34 出处:网络
I want to validate some asp.net textboxes w开发者_如何转开发ith the jQuery Validation plugin found at

I want to validate some asp.net textboxes w开发者_如何转开发ith the jQuery Validation plugin found at http://docs.jquery.com/Plugins/Validation, but it appears that the elements must be between a form tag. If I have just a couple elements, I would hardly call that a form, so I would rather not have them wrapped inside a form element. Is there a way around this? Also, if I have two buttons on the form, a cancel and a submit button and I want the form only to validate when the submit button is clicked, but not the cancel button, how is this accomplished?


I have just a couple elements, I would hardly call that a form, so I would rather not have them wrapped inside a form element.

If the elements are not within a form tag, then it is not a valid HTML document, so behavior within script might get wonky depending on how the browser deals with the malformed HTML.

Most browsers will create a form implicitly, but now you have no control over the form's behavior. The defaults are usually be a post action form targeted at the requested page's URL.

The problem is, you probably have no idea what selector to use in the JQuery to get a reference to the form... but I suppose $("form") would do the trick.

validate when the submit button is clicked, but not the cancel button

The plug-in intercepts and runs on the submit event of a form. Generally cancel buttons are html input elements with the type attribute set to "reset":

<input type="reset" value="cancel" />

A reset type button will not cause the form to submit, and this will not trigger the validation.

If you use another button type, make sure the onclick even returns false. This cancels the form's submit action but still allows you to run javasctipt of your own when the button is clicked.


The jquery validate plugin requires a form element to function, so you should have your form fields (no matter how few) contained inside a form.

You can tell the validation plugin not to operate on form submission, then manually validate the form when the correct submit button is clicked.

For example, using a class to identify the correct submit button:


$(document).ready(function() {
  var form = $("form");

  form.validate({
    onsubmit: false,
  });

  //Validate form only if validation submit button is clicked
  //Allows cancel submit buttons to function properly
  $('.validate', form).click(function() {
    if (form.valid()) {
      form.submit();
    }
    else {
      form.validate().form();
    }
  });

});
0

精彩评论

暂无评论...
验证码 换一张
取 消