HTML5 Input Pattern for Telephone Number

Matthew Felgate Source

I need 9-12 characters starting with 01, 02, 03, 07 or 08. Why is my pattern not working?



answered 1 month ago chevybow #1

This should work for you


Your issue was using [] instead of () checking for the first numbers. You need parenthesis with the logical ors. The way you had it you were matching literally against just one character of either any number or |.

For example:

012345678 would have matched, as would have |12345678 with the pattern you were using

answered 1 month ago Takit Isy #2

You don't need ^ and $.
I tried to simplify your pattern:

  • Changed [01|02…08] to 0(1|2…8) because you need to use parenthesis as chevybow explained,
  • Changed {8-10} to {7,10} because you said you “need 9-12 characters”, and - doesn't work in the {}.

This snippet works for me:

  <input pattern="0(1|2|3|7|8)[0-9]{7,10}" />
  <input type="submit" />

Hope it helps.

answered 1 month ago The fourth bird #3

I think you tried to use an alternation (01|02|03|07|08) instead of using the digits in a character class [01|02|03|07|08]

But even when you use the version with the alternation, that would match 2 digits and would in your regex be followed by [0-9]{8-10} which will be a total of matching 10 - 12 digits instead of the 9 - 12

You could put the prepending zero before the charcter class and leave 12378 inside the character class. That would be 2 characters, leaving matching 7 -10 following digits.

You don't need the ^ and $ because the regex is already anchored.


comments powered by Disqus