Regex Problem - Build a Telephone Number Validator

Hey everyone :wave:

I’m working on the “Build a Telephone Number Validator” project in the JavaScript course, and I’m trying to build a regex to match all valid formattings of a U.S. phone number. As far as I understand, a US phone number is very precisely formatted as such (I omitted the plus sign “+” in the country code because fCC did):

  • Optional country code “1”
  • Optional space " "
  • Optional opening parenthesis “(”
  • 3 digits
  • Optional closing parenthesis “)” (if opening parenthesis was used)
  • Optional space " " or dash “-”, but not both
  • 3 digits
  • Optional space " " or dash “-”, but not both
  • 4 digits

The examples of valid formatting provided by fCC for the project are:

1 555-555-5555
1 (555) 555-5555
1(555)555-5555
1 555 555 5555
5555555555
555-555-5555
(555)555-5555

To match this, I wrote the following regex and was testing it as follows:
const phoneRegex = /1? ?\(?\d{3}\)?( |-)?\d{3}( |-)?\d{4}/;

console.log(phoneRegex.test(/* Inputs here */));

Unfortunately, I’m not very good at regexes :sweat_smile:, and so some of the test strings that should return false returned true. For example,

const phoneRegex = /1? ?\(?\d{3}\)?( |-)?\d{3}( |-)?\d{4}/;

console.log(phoneRegex.test("qqqqdasdfsdf;34555555244444422255555"));

returns true, when it obviously shouldn’t. Please explain to me what I’m doing wrong.

Thank you very much!


Side question: How do I make the regex match if the first group of the three digits has parentheses around it, but only if both are there? That is, how to match

"1(234)5678912"

but not

"1(2345678912"

or

"1234)5678912"

Thank you very much!

Please post a link to this challenge.

I also edited the link into the main post :+1:

1 Like

Here is some infomation that may help. Good luck
Put your code const phoneRegex = /1? ?\(?\d{3}\)?( |-)?\d{3}( |-)?\d{4}/ into this online regex tool that shows what might be the problem regex101: build, test, and debug regex

That IS the entire JS file, for the time being. I’m figuring out the regex first and then the rest of the code.

I tried the website you linked, as well as another, and I concluded that it’s matching part of the string. For example,

const phoneRegex = /1? ?\(?\d{3}\)?( |-)?\d{3}( |-)?\d{4}/;

console.log(phoneRegex.test("qqqqdasdfsdf;34555555244444422255555"));

returns true because the regex matches 3455555524.

The question is, how do I make it so it only returns true if it’s a full match (i.e. it only returns true when everything in the string matches the regex and there isn’t any extra stuff)?

My answer is you are missing the anchors ^ and $ at the beginning and the end of this code.

1 Like

I just realized that as well! Thank you very much Rob. Cheers!

1 Like