1

I'm looking for something that will validate the following:

  • 13175551234
  • 3175551234

but NOT validate:

  • 1 (317) 531 1234
  • 1-317-555-1234

Basically it should validate 10 or 11 digit phone numbers that can optionally begin with 1 and don't contain spaces, hyphens or parentheses. The area code should not be optional either.

How can I do this?

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
whoblitz
  • 1,065
  • 1
  • 11
  • 17

3 Answers3

3

That's actually pretty straightforward: ^1?\d{10}$

Matt
  • 43,482
  • 6
  • 101
  • 102
  • 1
    This one allows phone numbers (without 1 for long distance) that start with 1. For instance, 155-555-5555 is not a valid US phone number, but your regex will accept it as such. (Not downvoting, as it's a good effort.) – Ken White Feb 22 '11 at 19:47
  • 2
    Let's hope he is using javascript... Otherwhise ৩৩৩৩৩৩৩৩৩৩ will be a valid number! (\d catches non-euro-american digits, that is the Bengali Digit Three U+09E9 :-) ) (Javascript considers digits only 0-9) – xanatos Feb 22 '11 at 19:53
  • Personal research on this suggests that RegexOptions.ECMAScript seems to remedy this and enable Jscript compliance. Kudos for the regular expression gentlemen. No Bengali nationals will be using my SMS notifications service for any would be nefarious plots or terrorist operations. – whoblitz Feb 22 '11 at 20:46
1

For something simple you could try this:

"^1?[0-9]{10}$"

Or slightly better:

"^1?[2-9][0-9]{9}$"

But this still matches incorrectly for some situations. For a better approach, see this answer:

Depending on the programming language you are using may want to use \d instead of [0-9]. But please be aware that in C# \d can match any digits as defined by the Unicode standard. So it can include Chinese numerals and other numeric characters that are illegal characters in a phone number. However [0-9] works everywhere, even in Unicode aware languages.

Community
  • 1
  • 1
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
0

Try this:

^1?[^0-1][0-9]{9}$

It matches

13155551212
3155551212

It doesn't match

03155551212
10315551212
1055551212
11555551212
Ken White
  • 123,280
  • 14
  • 225
  • 444