jQuery使用html5模式验证 [英] jquery validate with html5 pattern

查看:101
本文介绍了jQuery使用html5模式验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使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选项声明所有规则.

我不知道这是否更好",因为这纯粹是观点问题,但是只要您包含

演示: 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆