Telephone Number Validator help needed!

Telephone Number Validator help needed!
0

#1

Tell us what’s happening:
My code is working for every scenario except for one case starting with -1. Do you have any idea why only this doesn’t work? If it starts with any number other than 1, it is supposed to fail. It works with other tests starting with 2,3,4.

Your code so far


function telephoneCheck(str) {
  // Good luck!
  return  /^1{0,1}\d{10}$|^1{0,1}\(\d{3}\)\d{7}$/.test(str.replace(/[^0-9()]/gi, ""));
}

console.log(telephoneCheck("-1 (555)555-5555"));
console.log(telephoneCheck("2 (555)555-5555"));
console.log(telephoneCheck("3 (555)555-5555"));

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/telephone-number-validator


#2

Oh sorry I got it. I started my code by getting rid of all character except numbers and (). But I shouldn’t have deleted “-” which is deleting “-” in front of -1…

Just to keep the history. I updated my code as below and it works fine.
return /^1{0,1}\d{3}-?\d{3}-?\d{4}$|^1{0,1}(\d{3})\d{3}-?\d{4}$/.test(str.replace(/[^0-9()-]/gi, “”));


#3

in input use pattern="[0-9]{1,15}" that means you can use only numbers and from 1 to 15 char to be valid!


#4

Hi @bestdesign,
First of all, thanks for the answer. I understand what [0-9]{1, 15} means but I cannot relate how it is related to the initial problem that I posted. Can you explain a bit further?


#5

This pattern is for validate phone number allowed only as your title says validator?


#6

Hi ! Also, adding a test just for the minus sign would do it. For example:

var minus1= (/^-/i.test(str));
if (minus1 == true){return false;}

and THEN your first solution.
CHECKED, it works,
Glad you made it your way. Regards, Esteban


#7

Thank you very much for the answer.
Yes, I also tried this way and it works!