JavaScript Algorithms and Data Structures Projects - Telephone Number Validator

Tell us what’s happening:
Describe your issue in detail here.
I have tried everything but this one " telephoneCheck("55 55-55-555-5") should return false ." keeps returning true
Your code so far

function telephoneCheck(str) {
  if (str.indexOf("(") === -1 && str.indexOf(")") > -1) {
    return false
  } 

  if(str[0] === "-") {
    return false;
  }
  let polishedPhone = str.replace(/-| /g, "")

  if (str.indexOf(")") - str.indexOf("(") >= 5) {
    return false;
  }


  if (polishedPhone.indexOf("(") < polishedPhone.indexOf(")")) {
    polishedPhone = polishedPhone.replace(/\(|\)/g, "")
  }
  console.log(polishedPhone)
  if (polishedPhone.length === 10) {
    return true;
  } else if (polishedPhone.length === 11 && polishedPhone[0] === "1") {
    return true;
  }

  return false;
}

let result = telephoneCheck("55 55-55-555-5");
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/109.0.0.0 Safari/537.36

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

Link to the challenge:

Which part of your logic do you think should catch this bad number?

1 Like

I am not sure, thats why I asked for help.

I think you should reconsider the approach you are using. You are using regex but only for some very simple matching. I know regex can be a little intimidating, but it is made for this kind of problem. I’ll give you a hint, this can be solved with just one regex pattern. Granted, it will be a slightly more complex pattern then perhaps you have done so far, but I don’t think it makes use of anything you haven’t learned in previous challenges.

Another hint. Start out by creating a pattern that will match any allowable variation of the last seven numbers of the phone number. Then add to what you have to deal with the area code and possible 1 at the beginning. The tricky part is definitely the optional parens around the area code. The either both need to be there OR neither should be there.

1 Like

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