Xi Vix
Xi Vix

Reputation: 1361

html5 form validation - use pattern on optional field

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}"

Upvotes: 2

Views: 2334

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

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.

Upvotes: 3

Related Questions