5

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/

3
  • FYI you should be able to remove the ^ from that pattern (the regexes are always full match() style - see the MDN docs). Commented Nov 9, 2014 at 17:59
  • How can I add multiple pattern matching for OR condition Commented Aug 13, 2021 at 7:43
  • write a pattern that has or condition. I dont know how but it should be standard regex Commented Aug 17, 2021 at 6:59

1 Answer 1

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

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

Sign up to request clarification or add additional context in comments.

3 Comments

Tried same as yours it didn't work for mine. let be debug a bit if not i will paste a fiddle
@aWebDeveloper, it works when you declare it within .validate() but not when you declare it inline? Something else you haven't shown must be breaking it, so we need to wait for you to reproduce the issue within a jsFiddle.
i think i was missing additional methods

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.