Validate US Telephone Numbers Help!

Here is the RegEx I’ve written to test for valid US phone numbers, but the problem is that it allows phone numbers with only 1 parentheses to be passed as valid. How do I fix this?

Here is the expression:

/^(1\s?)?(?\d{3})?[- ]?(\d{3})[- ]?(\d{4})$/

Thanks for the help!

It says your regex is invalid.

I see a (? in your regex. I guess this is what makes it invalid. If you need to match parentheses, you need to prefix a backslash, like: \(?

It’s cool that you try to make complex regexps, but I think you don’t need it here. You can just cut off everything but numbers and parentheses and then you left with only 4 cases you need to check (without regexp). Of course, it’s just my way and you may choose your own.

If I take out the ? after the ( that’s before the d{3} I have what I think you intended to comment,

/^(1\s?)?
(\d{3})?
[- ]?
(\d{3})
[- ]?
(\d{4})$/

let’s look at the part you’re concerned about, the area code: (\d{3})?
first off, parenthesis need to be escaped ala \( when using them as a character rather than regex grouping.
we can either have 3 numbers, or 3 numbers surrounded by parens.
regex’s “or” operator is |, so let’s use that inside of a group
( \d{3} | \(\d{3}\) )?
so that will allow 3 numbers OR 3 numbers with parens on both sides, and not just one side or the other.

edit: ha, the edit pane was eating some of the chars in the code i wanted to show until i used preformatted text. probably happened to op too.

1 Like

Where did you find out the regex is invalid (I’m assuming there is a regex validation site) or did you just look into an error code/message that a browser spat out when you tried to code it. … Just wondering. -thanx

The FCC editor warns about it (a little warning sign appears next to its line number, saying the regex’s invalid). Same when I tried it in repl.it

I also like a site called regexlib.com that has a cheatsheet, a testing page, and of course a library of user-submitted regexes for different purposes

Thanks, and thanx for the quick response.

Yep, you’re right. When I copied and pasted the code into the edit pane it removed the ( in the code. Your suggestion did the trick though. Thanks!

Hi Gregg, I had the same problem OP was having. Thanks to your help (specifically this part ( \d{3} | (\d{3}) )? ) I was able to pass the challenge! :slight_smile: