Regular Expression (RegEx) For Phone Numbers With Country Code Check
I need a PHP RegEx through which I can validate a phone number format using the following criteria:
- Should not include anything except for numbers;
- Should not start with a zero as I need to have the country code prefixed;
- The list of allowed country codes should be there in RegEx;
- The digit immediately a开发者_StackOverflow中文版fter the country code should not be a zero;
- The maximum length of the number should not exceed 13 digits.
I have tried to search on Stack Overflow before posting this question but couldn't find the exact solution. Any help would be highly appreciated.
Edit: I just want the user to enter the phone number in a valid format as currently my clients do some silly formatting mistakes while writing it. I am not worried about it being actually valid (call-able) as the user will take care of that himself.
Regards
I wouldn't burn my fingers on this.
Just by looking at a phone number you can not judge whether it is valid or not, and even if it 'looks' valid it might not be the phone number you're looking for (ie. someone else's phone number).
You're trying to solve the problem at the wrong level. The only way to validate a phone number is to actually CALL it ;)
A regex that suffices your criteria:
/^(1|20|21|..etc)[1-9][0-9]+$/
list of country codes (seperated by | ) followed by a digit that is not 0, followed by any digit any number of times.
You can can't do the 13-length check and the country check in one regex because the length of the country codes vary (to my knowledge at least). You can do the 13-length check by a generic regex like:
/^.{,13}$/
Matching anything up to 13 characters long
The digit immediately after the country code should not be a zero;
That system will fail for Italy. The leading 0 for Italian phone numbers is dialled from abroad.
They might be some other countries where that also happens, but Italy is the most well-known.
The maximum length of the number should not exceed 13 digits.
For shorter numbers but with an extension added, that rule will be broken in multiple countries.
With 3 digit country code, 3 digit area code and 8 digit subscriber number, you're a digit short.
精彩评论