How can I validate an entire page with the jQuery Validate plugin?

混江龙づ霸主 提交于 2020-01-07 06:59:53

问题


Using the jQuery validate plugin is easy in certain situations, such as this, from the official docs, where are here:

<form class="cmxform" id="commentForm" method="get" action="">
  <fieldset>
    <legend>Please provide your name, email address (won't be published) and a comment</legend>
    <p>
      <label for="cname">Name (required, at least 2 characters)</label>
      <input id="cname" name="name" minlength="2" type="text" required>
    </p>
    <p>
      <label for="cemail">E-Mail (required)</label>
      <input id="cemail" type="email" name="email" required>
    </p>
    <p>
      <label for="curl">URL (optional)</label>
      <input id="curl" type="url" name="url">
    </p>
    <p>
      <label for="ccomment">Your comment (required)</label>
      <textarea id="ccomment" name="comment" required></textarea>
    </p>
    <p>
      <input class="submit" type="submit" value="Submit">
    </p>
  </fieldset>
</form>
<script>
$("#commentForm").validate();
</script>

But what if you don't have a "form" per se, but want to apply validation to your entire page?

I tried this:

$(window).load(function () {
    . . .
    this.validate();
});

...but it doesn't seem to work. Related question here.


回答1:


You need to validate the form. So you can validate using :

$('#commentForm').validate();

OR

$('#commentForm').valid();

On submit button click event




回答2:


But what if you don't have a "form" per se, but want to apply validation to your entire page?

The plugin most likely relies on the native (or jquery) submit() functionality. Anytime you are creating a form, you should try to use the <form> tag. At least for semantic reasons if nothing else.



来源:https://stackoverflow.com/questions/31708935/how-can-i-validate-an-entire-page-with-the-jquery-validate-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!