0

I have a web form and want to accept the following phone numbers in the following format:

1234567890 123-456-7890 123.456.7890 123-4567890

The first number cannot be a 0 or a 1.

How can I do this with regex/javascript? I found a few regex formulas online but none are specific to my needs

3 Answers3

1

null !== thenumber.match(/^[2-9][0-9]{2}[.-]?[0-9]{3}[.-]?[0-9]{4}$/);

(Edited to give slightly better answer with boolean result)

elixenide
  • 44,308
  • 16
  • 74
  • 100
0

Consider the following Regex...

[\d-[01]]\d{2}[-\.]?\d{3}[-\.]?\d{4}

Note: You examples start with a 1 which will not satisfy the above regex.

gpmurthy
  • 2,397
  • 19
  • 21
0

The user-provided format should be irrelevant. It makes more sense to store phone numbers as, well, numbers, i.e. digits only, and add uniform formatting when displaying them back. Otherwise you end up wit a mess in your database and you're going to have a hard time searching for numbers (if you wanted to find if given number is already in your DB then how'd you know the format it was typed in?), and you will have inconsistent formatting of numbers when displaying them.

So you'd store any of your example numbers as 1234567890, no matter what the user has typed into the form. Which means you can validate your input by stripping any non-digits, then checking the length and other conditions, like this:

function validPhone( num ){
   var digits = num.replace(/\D/g,'');
   // assuming 10 digits is a rule you want to enforce and the first digit shouldn't be 0 or 1
   return (parseInt(digits[0],10) > 1 && digits.length == 10); 
}

You could also use return parseInt(digits, 10) >= 2000000000 to validate that the number doesn't start with 0 nor 1 and has at least 10 digits.

pawel
  • 35,827
  • 7
  • 56
  • 53