1

Currently I am using a regular expression for validating numeric-only phone numbers which looks something like this:

/^([\d \-\)\(\+\.]{10,16})$/

I have a requirement where I need to upgrade the regular expression to support the below valid cases of phone numbers:

(866) 999-EMAS
1-800-MY-APPLE

Thanks

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Raghu
  • 2,543
  • 1
  • 19
  • 24
  • 1
    Are you talking about Javascript, Ruby, or iOS regexes? (you have tags for all of them). And have you tried anything, or do you just want us to implement your requirements? – tessi Nov 20 '13 at 23:14
  • @tessi This is for ruby regexes . I suppose regex's should be the same no matter what language you use. Shouldnt they? What I am trying is this ^([\d \-\)\(\+\.[a-zA-Z0-9]]{10,16})$. I am not sure if this will allow any invalid case as I am not a regex expert so i posted this question. – Raghu Nov 20 '13 at 23:16
  • *"I suppose regex's should be the same no matter what language you use"* In an ideal world yes, but different languages support different features of regular expressions, so it does matter. I removed the other tags since you seem to be interested in Ruby only. – Felix Kling Nov 21 '13 at 06:41

2 Answers2

2

There is no such thing as a regex to validate a phone number… Really, forget it. :-)

There are dozens of formats across the world, and sometimes within countries themselves. This means you've no guarantee whatsoever on the number of digits — which, btw, it can be as few as two, and perhaps even one, digits.

Adding insult to injury, each place seems to have its own way to present phone numbers: with local code and regional codes or without, with a slew of parenthesis, brackets, dashes, dots, spaces, letters, even words; you name it. In some countries, the locals can't even agree on how it's supposed to be formatted amongst themselves for the same number.

In the end, you might fix your regex by adding stuff in your brackets, e.g. [\d \-\)\(\+\.a-zA-Z]. But in the end it'll still be just as wrong as requiring a non-empty zip code, due to length considerations or some edge case involving bizarre characters that you've yet to identify.

The only way to truly be sure is to dial the number and actually place the call.

Denis de Bernardy
  • 75,850
  • 13
  • 131
  • 154
0

After tweaking my existing regular expression this is what I founds seems to work .

/^([\d \-\)\(\+\.[a-zA-Z0-9]]{10,16})$/
Raghu
  • 2,543
  • 1
  • 19
  • 24
  • Read the answer that says there's no answer. Then (until you learn to write automated tests to play "what if" with your code), learn Regexps with this non-sucky little web page: http://rubular.com/ – Phlip Nov 20 '13 at 23:29
  • Read http://stackoverflow.com/a/737464/128421. – the Tin Man Nov 21 '13 at 04:50