最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery validate with html5 pattern - Stack Overflow

programmeradmin3浏览0评论

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 /

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/2ma8ec6j/

Share Improve this question edited Nov 10, 2014 at 22:08 aWebDeveloper asked Nov 9, 2014 at 17:44 aWebDeveloperaWebDeveloper 38.4k41 gold badges175 silver badges247 bronze badges 3
  • FYI you should be able to remove the ^ from that pattern (the regexes are always full match() style - see the MDN docs). – declension Commented Nov 9, 2014 at 17:59
  • How can I add multiple pattern matching for OR condition – Siddhart hundare Commented Aug 13, 2021 at 7:43
  • write a pattern that has or condition. I dont know how but it should be standard regex – aWebDeveloper Commented Aug 17, 2021 at 6:59
Add a ment  | 

1 Answer 1

Reset to default 10

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/fLxgz9dn/

See: https://github./jzaefferer/jquery-validation/issues/785

发布评论

评论列表(0)

  1. 暂无评论