0

For an assignment, I was told to use the following regex in an HTML input pattern to validate a phone number, however no matter what I do I cannot get it to work. The browser just always throws an error saying it is invalid. I haven't heard back from my professor with an updated regex. Any help would be appreciated!

^\d{10}$|^(\(\d{3}\)\s*)?\d{3}[\s-]?\d{4}$

The valid phone numbers according to the provided regex would be:

1234567891

(123)4567891

(123) 4567891

(123)456-7891

(123) 456-7891

I have tried various different forms of the regex:

\d{10}|(\d{3} *)?\d{3}[ -]?\d{4}
\d{10}|(\(\d{3}\)\s*)?\d{3}[\s-]?\d{4}
\d{10}|(\d{3}[\s-]?)?\d{3}[\s-]?\d{4}
\d{10}\|(\(\d{3}\)\s*)?\d{3}[\s-]?\d{4}
\d{10}|\d{3}[\s-]?\d{3}[\s-]?\d{4}
\d{10}|(\d{3} *)?\d{3}[ -]?\d{4}
VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • How should we know what you consider a *"valid"* telephone number? You mean to create an international validation tool for phone numbers? Where's a sample of correct and incorrect entries? What is the first example for? What is the second? If those are your tries, the first is?... Have you tried to google *"`js regex validate phone number page:stackoverflow`"* ? If you did, why all the answers were unhelpful for your specific case? – Roko C. Buljan Aug 24 '23 at 18:47
  • Welcome! Have you tried to escape the hyphen? Like this: `[\s\-]` ([demo](https://jsfiddle.net/jm4a2c3q/1/)). If that's the reason, I would not have known this either. My understanding was that at the end of a character-class a hpyhen does not need to be escaped. :D Just played a bit with it to get it working. – bobble bubble Aug 24 '23 at 19:22
  • 1
    @bobblebubble Wow! I changed the provided regex to: \d{10}|(\(\d{3}\)\s*)?\d{3}[\s\-]?\d{4} and it is working now. I can't believe it was just one character missing. Thank you :) – divided_by_0 Aug 24 '23 at 20:04
  • @divided_by_0 I don't even know how to explain this, never came across it yet. Let's wait if someone puts a nice answer with any more information. You're welcome! – bobble bubble Aug 24 '23 at 21:07
  • 1
    That's some interesting finding (as usual) @InSync! :) – bobble bubble Aug 25 '23 at 02:29
  • 1
    We are going to see hundreds of questions like this now, I am afraid. – Wiktor Stribiżew Aug 25 '23 at 08:25

0 Answers0