Validate US Telephone Numbers-5 won't pass

This is my code:

function telephoneCheck(str) {
var char=/(?:1|\d{3}|(\d{3}))([-\s])\d{3}\1\d{4}/;
var check=char.test(str);

return check;

I have 5 phone numbers that won’t pass as true or false. They are:
telephoneCheck(“1 (555) 555-5555”) should return true.
telephoneCheck(“5555555555”) should return true.
telephoneCheck("(555)555-5555") should return true.
telephoneCheck(“1(555)555-5555”) should return true.
telephoneCheck("(555-555-5555") should return false.

I have played with my regexp on to no avail.

What am I missing in my code?


I feel like you’re trying to combine too much validation into a single regex. How about taking it in steps?

Remove non numerical characters from the whole string (spaces, parentheses, dashes)
Check for length (must be 10 or 11 characters long)
If 11 characters long, is the first character a 1?
Validate what’s left.

This way you’re sequentially stripping out garbage until you can apply your final validation. After you get that right, if you want to tighten it up, then you can start combining these things into a single regex.

You should separate first number and space, escape the parenthesis, and check only for space and not ‘-’ on first 3 numbers.