Javascript jquery 使用 html5 模式验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26831180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery validate with html5 pattern
提问by aWebDeveloper
How do i make jQuery validate/support an HTML 5 pattern? It would be great if it did without specifying the pattern on each field.
我如何让 jQuery 验证/支持 HTML 5 模式?如果没有在每个字段上指定模式,那就太好了。
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/
回答by Sparky
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 somerules via inline HTML attributes. However, you can declare allrules via the rulesoption within .validate()or the .rules()method.
您可以通过内联 HTML 属性声明一些规则。但是,您可以通过选项内或方法声明所有规则。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.jsOR the pattern.jsfile, the jQuery Validate plugin will pickup and use the HTML5 patternattribute.
我不知道这是否“更好”,因为这纯粹是一个意见问题,但是只要您包含additional-methods.jsORpattern.js文件,jQuery Validate 插件就会选取并使用 HTML5pattern属性。
<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

