开发者

Is it possible to create a mask to handle non-north american phone numbers?

开发者 https://www.devze.com 2023-01-20 20:32 出处:网络
For north american phone numbers, (999) 999-9999 works pretty well for an input mask. However, I can\'t find a good example that will handle non-north american numbers.I know that the number of digit

For north american phone numbers, (999) 999-9999 works pretty well for an input mask.

However, I can't find a good example that will handle non-north american numbers. I know that the number of digits can vary, so other than restricting it to digits only, is th开发者_如何转开发ere a good example anywhere?


There is no generic mask, really: There are too many combinations.

The only thing that is fixed is the international country code, usually prefixed by +.

According to the Wikipedia Article on telephone numbering plans, most countries conform with the E.164 numbering plan.

If I read E.164 correctly, you can safely make the following assumptions:

  • Country code: 1-3 digits

  • Network / Area code and Number: Up to 19 digits

I would ask for the country code, and have the "area code + number" field as a 19-digit input.


You can deduce the country code with a simple RegEx such as:

^(?:(?:0(?:0|11)\s?)|+)([17]|2([07]|[1-689]\d)|3([0-469]|[578]\d)|4([013-9]|2\d)|5([1-8]|[09]\d)|6([0-6]|[789]\d)|8([12469]|[03578]\d)|9([0-58]|[679]\d))

Followed by

(([\s\(\).-]{0,2}\d){4,13})$

to extract the national number.

For validating the national number length and validity, you'd need libphonenumber or similar.

The long RegEx above allows +, 00 or 011 before the country code and a selection of punctuation in the number which will also have to be stripped.


You don't mention your application but this is certainly possible using regular expressions. You might want to take a look here.


Not easily. Take a look at this page for an example why: if you only look at the German phone numbers, you'll note that there are different formats depending on where you're calling the number from. Which one do you pick? And that's just for German phone numbers; they differ from continent to continent, and from country to country.

Going with "numbers-only" is probably your safest bet.


I would allow for spaces, dashes, slashes and all that, but actually only care for numbers and the optional leading + sign. Everything else, such as assuming certain blocks of a certain length is just asking for trouble.


May be it is bad to answer an old question. But libphonenumber seems like a good solution to your question.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号