I'm trying to write a RegEx to test if a number is valid and for valid I mean any number that matches country calling codes but also where the format of telephone numbers is standardized by ITU-T in the recommendation E.164. This specifies that the entire number should be 15 digits or shorter, and begin with a country prefix as said here so I did this:

^\+\d{2}|\d{3}([0-9])\d{7}$

But it's not working. In my case (VE numbers can't match the RegEx since this one are validated in another way) this input is valid:

+1420XXXXXXXXXXX // Slovakia - X is a digit and could be more, tough, 5 minimum
001420XXXXXXXXXX // Slovakia - I've changed from + to 00
420XXXXXXXXXXXXX // Slovakia - I've removed the 00 o + but number still being valid
+40XXXXXXXXXXXXX // Romania

Invalid numbers are the one that doesn't match the RegEx and the one started with +58 since they are from VE. So, resuming, a valid number should have:

  • +XX|+XXX plus 12|11 digits (5 minimum) where XX|XXX is the country code and then since maximum is 15 digits then should be 12 or 11 digits depending on the country format

Can any help me with this? It's a one I called complex

share|improve this question
up vote 1 down vote accepted

Few strange things going on with your regexp:

  • \d is shorthand for [0-9] - fine to use both, but I'm wondering why they're mixed
  • what you are searching with you OR (|) is "something that starts with +XX" i.e. plus and two numbers (^\+\d{2}) OR "something that ends with XXXXXXXXXXX" i.e. 11 numbers (\d{3}([0-9])\d{7}$)
    • You need to group (with brackets) the OR choices, otherwise it is everything to the left or everything to the right (simplistically)
    • ^\+(\d{2}|\d{3})([0-9])\d{7}$

There is, however, another way of giving the number of occurrences : {m,n} means occurs between m and n times. So you could say ^\+\d{7,15}$ (where 7 is your minimum 5 + the minimum country code of 2).

To really do this, however, you might want to take a look here (https://code.google.com/p/libphonenumber/ 1) where there is a complete validation and formatting for all phone numbers available as javascript.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.