简体   繁体   English

国际电话号码的Javascript正则表达式

[英]Javascript Regular Expression for International Phone Number

The following regular expression isn't working for international phone numbers that can allow up to 15 digits: 以下正则表达式不适用于最多允许15位数的国际电话号码:

^[a-zA-Z0-9-().\s]{10,15}$

What needs to be adjusted? 需要调整什么?

You may find the following regex more useful, it basically first strips all valid special characters which an international phone number can contain (spaces, parens, + , - , . , ext ) and then counts if there are at least 7 digits (minimum length for a valid local number). 您可能会发现以下正则表达式更有用,它基本上首先删除国际电话号码可以包含的所有有效特殊字符(空格,parens, +-.ext ),然后计算是否至少有7位数(最小长度)有效的本地号码)。

function isValidPhonenumber(value) {
    return (/^\d{7,}$/).test(value.replace(/[\s()+\-\.]|ext/gi, ''));
}

Try adding a backslash: 尝试添加反斜杠:

var unrealisticPhoneNumberRegex = /^[a-zA-Z0-9\-().\s]{10,15}$/;

Now it's still not very useful because you allow an arbitrary number of punctuation characters too. 现在它仍然不是很有用,因为你也允许任意数量的标点字符。 Really, validating a phone number like this — especially if you want it to really work for all possible international phone numbers — is probably a hopeless task. 真的,验证这样的电话号码 - 特别是如果你想让它真正适用于所有可能的国际电话号码 - 可能是一个绝望的任务。 I suggest you go with what @BalusC suggests. 我建议你选择@BalusC建议的内容。

and then counts if there are at least 7 digits (minimum length for a valid local number). 然后计算是否至少有7位数(有效本地号码的最小长度)。

The shortest local numbers anywhere in the world are only two or three digits long. 世界上任何地方最短的本地号码只有两到三位数。

There are many countries without area codes. 有许多国家没有区号。

There are several well-known places with a 3 digit country code and 4 digit local numbers. 有几个众所周知的地方有3位国家代码和4位本地号码。

It may be prudent to drop your limit to 6 or 5; 将你的限制降到6或5可能是谨慎的; just in case. 以防万一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM