Telephone # Validator

Hi guys, can someone please check my code and see what I’ve done wrong.
It says that it needs to return to false, and I can’t seem to figure out the issue.

Your code so far


function telephoneCheck(str) {
if (str.indexOf("(") === -1 && str.indexOf (")") > - 1) return false;
if (str.indexOf(")") - str.indexOf("(") >= 5) return false;
if (str[0] === "-") return false;

let polishedPhone = str.replace(/-| /g, "");

if (polishedPhone.indexOf("(") < polishedPhone.indexOf(")")) {
polishedPhone = polishedPhone.replace(/\(|\)/g, "");
}


if (polishedPhone.length === 10) {
return true;
} else if (polishedPhone.length === 11 && polishedPhone[0] === "1") {
return true;
}

return false;

}

let result = telephoneCheck ("1 (555) 555-5555");
console.log(result);

Your browser information:

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

Challenge: Telephone Number Validator

Link to the challenge:

I think you should reconsider how you are solving this. Problems like these are made for regular expressions.

1 Like

The one failing test is this one:

telephoneCheck("55 55-55-555-5") should return false.

After you create your polishedPhone variable, your telephone string is 5555555555. It goes into if (polishedPhone.length === 10), which is true, so your function returns true. To avoid that, you’d have to implement some logic to check if the groups of numbers have the right lengths - before you remove all dashes and spaces.

But as mentioned above, you can solve this challenge with one line of regex.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.