Phone Number Validator Help

I’m having trouble with my code here. If I test the regex on the string and as it to return true it will return true for all the ones that should return true and if I test it and ask it to return false then it will return false, but it will not return both. I can’t get it to return the true AND false cases. It will only output true if I have a return true outside of the if statement without the else return false statement afterwards. If I write and if else statement then it will only return the else statement result.

function telephoneCheck(str) { 
  const regex = /^(1)\s?\(d{3}\)([-\s]?)d{3}([-\s]?)\d{4}/

  if (regex.test(str)) { 
    return true; 
  } else if (regex.test(str) == false) {
    return false;
  } 
} 
console.log(telephoneCheck("1 (555) 555-5555"));

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

Challenge: JavaScript Algorithms and Data Structures Projects - Telephone Number Validator

Link to the challenge:

You’ve got a bunch of unnecessary syntax in the regex string (particularly parentheses). It doesn’t necessarily hurt you but it makes your regex harder to read, so I would try to only include the bare minimum needed.

I would start by creating a regex just for a basic phone number (areacode-prefix-number). Don’t worry about the possible 1 at the beginning or the parentheses around the area code yet. Once you have that basic number working then you can start adding the extras, such as the missing dashes in between the numbers, or the possibility of a 1 at the beginning, or the possibility of parentheses around the area code.

Hint: Don’t forget that a regex has an “OR” operator.

Also, do you really need all of this? What is the return value of RegExp.test()?

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