Telephone Number Validator does not pass tests

Tell us what’s happening:

I checked this regex with the test cases in regex101.com and it matched the correct numbers and didn’t match the wrong numbers, but it doesn’t pass in FreeCodeCamp. What am I doing wrong?

Your code so far


function telephoneCheck(str) {
let regex = new RegExp(/\d{3}[- ]?\d{3}[- ]?\d{4}|\(\d{3}\)[ ]?\d{3}-\d{4}|^[1] \d{3} \d{3} \d{4}|^[1] \(\d{3}\) \d{3}-\d{4}|^[1]\(\d{3}\)\d{3}-\d{4}/);
console.log(regex.test(str));
return regex.test(str);
}
telephoneCheck("555-555-5555");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36.

Challenge: Telephone Number Validator

Link to the challenge:

Hello!

Did you try the tests that do not pass on regex101.com? Once you run the tests, there is a list with the tests that fail and the expected result.

For instance, your regex matches 6054756961 which, as per the challenge requirement, is wrong. It should return false.

This one -1 (757) 622-7382 also returns true whereas it’s required to return false.

2 Likes

Thank you for your answer!

Why should 6054756961 not pass? In the exercise it says The following are examples of valid formats for US numbers (refer to the tests below for other variants):

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

What’s the difference between 6054756961 and 5555555555? They both have ten digits.

And according to regex101.com -1 (757) 622-7382 doesn’t pass the test. The only one that should not pass the test (I still don’t get why) and does is 6054756961. However, in FCC a lot of numbers that don’t pass in regex101 pass.

can you show what do you mean that in regex101 it doesn’t pass?
have you used the unit tests? or what?

The ones that are at the bottom don’t fully pass (except for 6054756961, that I don’t know why it shouldn’t pass). Yet in FCC they return true, and in regex101 they don’t since they are not a full match.

if the test method find a substring that match the pattern will return true

like if you do /a/.test("bcad") it will return true because the string contains an a, as long as there is even a single character matched, the test method returns true
if the string stay completely not highlighted then it returns false

1 Like

Oh! And how do I do for it to be exclusive? To only return true if all the string is like the regex.

you need to find the way to say that the matched substring must be all the string

you have met the way in the regex part. Maybe you need a refresh, like a regex cheat sheet, or try to google how to do that

I finally solved it like this:

[SOLUTION]

function telephoneCheck(str) {
    let regex = new RegExp(/^(1\s?)?(\(\d{3}\)|\d{3})[- ]?\d{3}[- ]?\d{4}$/);
    return regex.test(str);
  }
  telephoneCheck("555-555-5555");
1 Like