jquery validate with html5 pattern

回眸只為那壹抹淺笑 提交于 2019-12-23 13:05:15

问题


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/


回答1:


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



来源:https://stackoverflow.com/questions/26831180/jquery-validate-with-html5-pattern

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