Reputation: 1662
I try to write a regex that will check validity of phone number inputs. There are several rules:
I managed to come up with this:
^(\+|\()?(\)?|\ *|\d{8,11})$
The problem is that this only matches 8-11 digits in a row, but the digits can be anywhere, only their total count should be 8-11.
Upvotes: 1
Views: 3246
Reputation: 476574
I assume you want to implement this format but without dashes? Furthermore there are more strict rules if you want to parse American telephone numbers. Please update your question and be more specific.
This regex can be used to match all 8-11
digits with a plus in front.
^\+?( *\d){8,11} *$
The interesting part is the ( *\d){8,11} *
. Each group between the brackets matches an unlimited number of spaces (can be zero, followed by a digit). So in total you have 8
to 11
digits and the spaces in between are unconstrained. You also need to put *
at the end to handle tailing spaces.
Now the problem is more complicated if you want to allow brackets, because the brackets also take some numbers. In case the total amount of digits is fixed to three), you can write it as
^\(( *\d){3} *\)( *\d){5,8} *$
Now you can generalize this method and produce:
^\(( *\d){1} *\)( *\d){7,10} *$
^\(( *\d){2} *\)( *\d){6,9} *$
^\(( *\d){3} *\)( *\d){5,8} *$
^\(( *\d){4} *\)( *\d){4,7} *$
^\(( *\d){5} *\)( *\d){3,6} *$
^\(( *\d){6} *\)( *\d){2,5} *$
^\(( *\d){7} *\)( *\d){1,4} *$
^\(( *\d){8} *\)( *\d){0,3} *$
^\(( *\d){9} *\)( *\d){0,2} *$
^\(( *\d){10} *\)( *\d){0,1} *$
^\(( *\d){11} *\) *$
And now it's only a matter of combining them:
^(\+?( *\d){8,11} *)|
\(( *\d){1} *\)( *\d){7,10} *|
\(( *\d){2} *\)( *\d){6,9} *|
\(( *\d){3} *\)( *\d){5,8} *|
\(( *\d){4} *\)( *\d){4,7} *|
\(( *\d){5} *\)( *\d){3,6} *|
\(( *\d){6} *\)( *\d){2,5} *|
\(( *\d){7} *\)( *\d){1,4} *|
\(( *\d){8} *\)( *\d){0,3} *|
\(( *\d){9} *\)( *\d){0,2} *|
\(( *\d){10} *\)( *\d){0,1} *|
\(( *\d){11} *\) *$
But I think @DaveKirby makes a valid point here. The rules differ that much between different regions and in time (who says we will write phone numbers the same way within 20 years?) that you better don't aim to capture them.
Upvotes: 2
Reputation: 406
Duplicate of A comprehensive regex for phone number validation
This question is pretty complicated when it comes to supporting international phone numbers, because rules may vary a lot from one country to another, or in some (big) countries like Brazil the rules may vary from mobile to landline for example.
Upvotes: 0