jQuery使用html5模式验证 [英] jquery validate with html5 pattern
问题描述
如何使jQuery验证/支持HTML 5模式?如果没有在每个字段上指定模式,那就太好了.
我知道我可以做到这一点(如下),但是还有更好的方法吗?
$("form").validate({
rules: {
"password": {
pattern: /[A-Za-z0-9\w]{4,20}/,
}
}
});
请参见小提琴 http://jsfiddle.net/2ma8ec6j/
引用:
如何使jQuery验证/支持HTML 5模式?"
它已经做到了.见下文
如果没有在每个字段上指定模式,那就太好了."
如果您不指定此位置,它将如何知道哪个模式转到哪个字段?
"...还有更好的方法吗?"
您可以通过内联HTML属性声明一些规则.但是,您可以通过.validate()
或.rules()
方法中的rules
选项声明所有规则.
我不知道这是否更好",因为这纯粹是观点问题,但是只要您包含 pattern.js
文件,jQuery Validate插件将提取并使用HTML5 pattern
属性.
<input type="text" name="somename" pattern="[A-Za-z0-9\w]{4,20}" />
演示: http://jsfiddle.net/fLxgz9dn/ >
请参阅: https://github.com/jzaefferer/jquery-validation/issues/785
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.
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/
Quote:
"How do i make jQuery validate/support an HTML 5 pattern?"
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. However, you can declare all rules via the rules
option within .validate()
or the .rules()
method.
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.
<input type="text" name="somename" pattern="[A-Za-z0-9\w]{4,20}" />
DEMO: http://jsfiddle.net/fLxgz9dn/
See: https://github.com/jzaefferer/jquery-validation/issues/785
这篇关于jQuery使用html5模式验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!