简体   繁体   English

jquery用html5模式验证

[英]jquery validate with html5 pattern

How do i make jQuery validate/support an HTML 5 pattern? 如何让jQuery验证/支持HTML 5模式? It would be great if it did without specifying the pattern on each field. 如果没有在每个字段上指定模式,那将会很棒。

I know I could do this (below), but is there better way? 我知道我可以这样做(下图),但有更好的方法吗?

$("form").validate({
  rules: {
    "password": {
      pattern: /[A-Za-z0-9\w]{4,20}/,
    }
  }
});

See Fiddle http://jsfiddle.net/2ma8ec6j/ 见小提琴http://jsfiddle.net/2ma8ec6j/

Quote : Quote

"How do i make jQuery validate/support an HTML 5 pattern?" “我如何让jQuery验证/支持HTML 5模式?”

It already does. 它已经做到了。 See below 见下文

"It would be great if it did without specifying the pattern on each field." “如果不指定每个领域的模式,那将会很棒。”

How will it know which pattern goes to which field if you don't specify this someplace? 如果你没有在某个地方指定这个模式,它将如何知道哪个模式进入哪个字段?


"...is there better way?" “......还有更好的办法吗?”

You can declare some rules via inline HTML attributes. 您可以通过内联HTML属性声明一些规则。 However, you can declare all rules via the rules option within .validate() or the .rules() method. 但是,您可以通过声明所有的规则, rules中选择.validate().rules()方法。

I don't know if this is "better" as that is purely a matter of opinion, but as long as you include the additional-methods.js OR the pattern.js file, the jQuery Validate plugin will pickup and use the HTML5 pattern attribute. 我不知道这是否“更好”,因为这纯粹是一个意见问题,但只要你包含additional-methods.jspattern.js文件,jQuery Validate插件就会拾取并使用HTML5 pattern属性。

<input type="text" name="somename" pattern="[A-Za-z0-9\w]{4,20}" />

DEMO: http://jsfiddle.net/fLxgz9dn/ 演示: http//jsfiddle.net/fLxgz9dn/

See: https://github.com/jzaefferer/jquery-validation/issues/785 请参阅: https//github.com/jzaefferer/jquery-validation/issues/785

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM