Regular Expression (RegEx) For Phone Numbers With Country Code Check

巧了我就是萌 提交于 2019-12-10 14:59:17

问题


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 after 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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/5777375/regular-expression-regex-for-phone-numbers-with-country-code-check

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!