2

I'm trying to make a javascript function with a regex, that will validate a phone number.

the rules are :
1. numbers only. 2. more then 10 numbers. 3. a dash ( - ) is allowed (optional).

first, I tried this one :

  function validatePhone(phone) {

        var phoneReg = /[0-9]{10,}/;
        return (phoneReg.test(phone));
    }

it worked well only on the first 2 rules, but not with the dash.

Then I tried var phoneReg = /[-0-9]{10,}/; and even var phoneReg = [\d]+\-?[\d]+ but then the javascript was broken...

any thoughts ?

thormayer
  • 1,070
  • 6
  • 28
  • 49
  • 3
    *"I'm trying to make a javascript function with a regex, that will validate a phone number."* That's your first mistake. :-) Even in the U.S., phone numbers can be complex (extensions and whatnot), and if you're dealing with anything that crosses country lines, all bets are off. Usually best to let people write what they write, make sure it's not blank, and have them double-check. FWIW. – T.J. Crowder Sep 27 '12 at 15:01
  • @T.J.Crowder thanks man, but its only in my country. which is very particular . thanks again for the concern. – thormayer Sep 27 '12 at 15:06
  • http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation – jbabey Sep 27 '12 at 15:11
  • @thormayer: You don't have extensions in your country? E.g., `Work number: [01234567891 ext 332]`? – T.J. Crowder Sep 27 '12 at 16:20

2 Answers2

3

This is how I would approach phone number validation:

var validatePhone = function(phone) {

  // Stip everything but the digits.
  // People like to format phone numbers in all
  // sorts of ways so we shouldn't complain
  // about any of the formatting, just ensure the
  // right number of digits exist.
  phone = phone.replace(/\D/g, '');

  // They should have entered 10-14 digits.
  // 10 digits would be sans-country code,
  // 14 would be the longest possible country code of 4 digits.
  // Return `false` if the digit range isn't met.
  if (!phone.match(/\d{10,14}/)) return false;

  // If they entered 10, they have left out the country code.
  // For this example we'll assume the US code of '1'.
  if (phone.length === 10) phone = '1' + phone;

  // This is a valid number, return the stripped number
  // for reformatting and/or database storage.
  return phone;
}
Casey Foster
  • 5,982
  • 2
  • 27
  • 27
2

This should work. The - character needs to be escaped.

var phoneReg = /[0-9-\-]{11,}/;

The potential problem with this, is that strings that have multiple dashes will test positive even when 10 numbers aren't in the string. I would suggest replacing dashes before testing.

var phoneReg = /[0-9]{11,}/;
return (phoneReg.test(phone.replace(/\-/g, '')); 
Austin Brunkhorst
  • 20,704
  • 6
  • 47
  • 61