True / False - Phone project Certificate

Hello dear community, I’m sitting on the phone validator right now. i don’t quite understand why my code isn’t working.

Telephone-Numer-Validator

Each number is returned as true.

###UPDATE###
In the description you will now also find the link. I have reworked the code again, unfortunately it still only returns false.

Maybe someone has a hint.

function telephoneCheck(str) {

  const validNum = [
    //555-555-5555
    /^\d{3}-\d{3}-\d{4}$/,

    //1 555 555 5555
    /^1 \d{3}\ \d{3}\ \d{4}$/,

    //(555)555-5555
    /^\(\d{3}\)\d{3}-\d{4}$/,

    //(555) 555-5555
    /^\(\d{3}\)\ \d{3}-\d{4}$/,

    //555 555 5555
    /^\d{3}\ \d{3}\ \d{4}$/,

    //5555555555
    /^\d{10}$/,

    //1 555-555-5555
    /^1 \d{3}-\d{3}-\d{4}$/,

    //1 (555) 555-5555
    /^1 \(\d{3}\)\ \d{3}-\d{4}$/,

    //1(555)555-5555
    /^1\(\d{3}\)\d{3}-\d{4}$/,

    //(555)555-5555
    /^\(\d{3}\)\d{3}-\d{4}$/,

    //1 555 555 5555
    /^1 \d{3} \d{3} \d{4}$/
  ];

for (var i = 0; i < validNum.length; i++) {
      return validNum[i].test(str);
  }
      return false;
}

telephoneCheck("555-555-5555");

//false
console.log(telephoneCheck("2(757)622-7382"));
//true
console.log(telephoneCheck("1 555 555 5555"))
//FINAL CODE ! (= !
function telephoneCheck(str) {

  const validNum = [
    //555-555-5555
    /^\d{3}-\d{3}-\d{4}$/,

    //1 555 555 5555
    /^1 \d{3}\ \d{3}\ \d{4}$/,

    //(555)555-5555
    /^\(\d{3}\)\d{3}-\d{4}$/,

    //(555) 555-5555
    /^\(\d{3}\)\ \d{3}-\d{4}$/,

    //555 555 5555
    /^\d{3}\ \d{3}\ \d{4}$/,

    //5555555555
    /^\d{10}$/,

    //1 555-555-5555
    /^1 \d{3}-\d{3}-\d{4}$/,

    //1 (555) 555-5555
    /^1 \(\d{3}\)\ \d{3}-\d{4}$/,

    //1(555)555-5555
    /^1\(\d{3}\)\d{3}-\d{4}$/,

    //(555)555-5555
    /^\(\d{3}\)\d{3}-\d{4}$/,

    //1 555 555 5555
    /^1 \d{3} \d{3} \d{4}$/
  ];

for(var i = 0; i < validNum.length; i++) {
  if (validNum[i].test(str))
  return true;
}
  return false;
}

telephoneCheck("555-555-5555");

//false
console.log(telephoneCheck("2(757)622-7382"));
//true
console.log(telephoneCheck("1 555 555 5555"))

You cannot return false when just one of the pattern does not match. You return false only after all patterns do not match.

The comparison test is == or ===.

Also note that you can solve this problem using fewer regex.

Please link to the specific challenge as well.

You’re code below isn’t properly validating the REGEX.

This section if (str = validNum[i]) is performing an assignment. It says, set the variable str to the value of validNum[i]. The result of this expression is a truthy value Truthy - MDN Web Docs Glossary: Definitions of Web-related terms | MDN. I think you’re actually trying to perform a test to see if the variable str matches the REGEX. So you would want to write something closer to validNum[i].test(str) .

1 Like

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