Validate Phone numbers

Validate Phone numbers
0

#1

I’m really close to the validate phone numbers solution. However, I’m wondering why I’m getting tripped up on the parentheses… I’m checking my regex with this site: http://www.regexpal.com/
Basically, my regex is not catching if the parentheses are in the right spot or not.

function telephoneCheck(str) {
  var re = /[^0-9 )(-]+/g;
  var re2 = /[0-9]/g;
  if (str.match(re)) {
    return false;
  }

  if (str.match(re2).length > 11 || str.match(re2).length < 10) {
    return false;
  }
  if (str.match(re2).length === 11 && str[0] !== "1") {
    return false;
  }
  var whole1 = /1?[-(]|\s?\d{3}[-)]|\s?\d{3}-|\s?\d{4}/g;
  if (str.match(whole1)) {
    return true;
  } 
}

Why does my code allow such things as

(5551239900)

or

213)4550018

Is there a way to say “only match the parentheses if there are open and closed and they are in the right spot”?


#2

use a regex conditional http://www.rexegg.com/regex-conditionals.html#syntax


#3

Thanks for the response! My problem is I am using conditionals already, but I think I need to make a conditional within a conditional. My regex currently:

/1?[-(]|\s?\d{3}[-)]|\s?\d{3}-|\s?\d{4}/g

I have 1? (start with a 1 or nothing), followed by [-(]|\s? (then have an open parenthesis, hyphen, whitespace, or nothing), then my three digits, then closed parenthesis, hyphen, whitespace, or nothing.

How do I set up to require both or no parenthesis? I tried:

(?[-(]|\s)?

but that is invalid… How do I say “If open parenthesis, then 3 digits, followed by closed parenthesis, or just three digits?”


#4

Did you solve it already?