2

I have an optional form field that I want to use the new html5 pattern option. But, when I add the pattern, the field becomes required even though I do not have the required attribute. I have included the pattern below. I want the user to be able to leave the field blank, but if the user enters something in the field, then I want the pattern applied. How would I accomplish this? Thanks in advance.

pattern="[-a-zA-Z '.,]{3,50}"
0

1 Answer 1

3

The problem is that {3,50} limiting quantifier requires at least 3 occurrences of the chars defined in the character class.

You need to make the pattern optional. Wrap it with an optional non-capturing group:

pattern="(?:[-a-zA-Z '.,]{3,50})?"
         ^^^                   ^^

HTML5 patterns are wrapped with the anchors automatically, i.e. the pattern above will be translated into ^(?:(?:[-a-zA-Z '.,]{3,50})?)$ and will match

  • ^(?: - start of the string
  • (?:[-a-zA-Z '.,]{3,50})? - 1 or 0 occurrences of 3 to 50 hyphens, ASCII letters, spaces, ', . or ,
  • )$ - end of string.
Sign up to request clarification or add additional context in comments.

2 Comments

Amazing. Thanks. You are HTML5 genius. I simplified it by removing the ?: at the front. And I didn't see the end of string in your pattern above. The simplified version worked. Is there a reason I need a start of string and end of string?
@XiVix: See the docs. The pattern you use in pattern attribute must match the entire string, and thus the ^ and $ in leading/trailing positions are not necessary. That is why I did not include them into the pattern.

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.