-2

I'm trying to validate a phone number in javascript with the following regex

var phoneExpression = /^\(?([0-9]{9})\)?$/;

this expression works with xxxxxxxxx number but i need a regex for xxxxxxxxx , +xx xxxxxxxxx and +x xxxxxxxxx and all i've tried fails.

AFS
  • 317
  • 1
  • 4
  • 7
  • So there was no single answer to one of the identical questions here on SO that worked for you ? How did they not work, what's different about your question? http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation, http://stackoverflow.com/questions/14639973/javascript-regex-what-to-use-to-validate-a-phone-number etc. – GitaarLAB Jan 09 '15 at 18:42
  • `.*` is the best answer.. Anything else is a good way to ask for trouble and drive (potential) customers to the competition that *did* do the *right* thing. Otherwise.. next one goes implementing e-mail validation, make assumptions about people's names and all that (high-school) jazz. What you *should* do, is: simulate client-side what your serverside will reject. – GitaarLAB Jan 09 '15 at 18:50
  • @GitaarLAB, I believe `/\+?[0-9 -\.]+/` is the most common. – Ruben Kazumov Jan 09 '15 at 20:02
  • @RubenKazumov: Yes indeed along those lines (I'd include `(` and `)`). The key point here is that one should stop thinking in terms of validation ('dictating' what a valid number is according to the programmer), whilst maintaining the useful part: 'instantly' indicating to the user (before submitting) that something is surely going to be rejected by the server: things like a number is not going to be smaller then x or larger then y and can only contain `+-() 1-9` characters etc. – GitaarLAB Jan 09 '15 at 20:30
  • @GitaarLAB: I absolutely agree with you and on your side! I believe, the validation should be, but the validation process should include: a) understanding the input; b) correction the input and c) verification of the input. It is not the rules of the textbox filling we delivering information to user about. Therefore, there is no problem to regex-ing any kind of input and even checking the numbers by global database prefixes, counties and sending text messages in background))) – Ruben Kazumov Jan 09 '15 at 21:15

2 Answers2

1

You want this one:

/^(\+\d{1,2}\s)?\d{9}$/

Mathes all of these:

123456789
+1 123456789
+12 123456789

Does NOT match these:

+12123456789
+12 12345678

...and here's an annotation:

/
    ^             // String start
    (
        \+        // Plus sign
        \d{1,2}   // One or two digits
        \s        // Whitespace
    )?            // The whole prefix group is optional
    \d{9}         // 9 digits
    $             // String end
/g
Andrew Dunai
  • 3,061
  • 19
  • 27
0
^\+?(([0-9]{1})*[- .]*([0-9]{3})*[- .]*[0-9]{3}[- .]*[0-9]{6})+$

should match the strings you are looking for

SNAG
  • 2,011
  • 2
  • 23
  • 43