电话号码验证 Javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6195458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Phone Number Validation Javascript
提问by Pit Digger
I want users to allow only phone numbers in following format
我希望用户只允许以下格式的电话号码
xxx-xxx-xxxx or xxxxxxxxxx all digits only . Can some one suggest a regular expression to do this ?
xxx-xxx-xxxx 或 xxxxxxxxxx 仅所有数字。有人可以建议一个正则表达式来做到这一点吗?
回答by Alex Aza
Something like this:
像这样的东西:
\d{3}-\d{3}-\d{4}|\d{10}
回答by Rob Raisch
While general phone number validation is a larger problem than what you're trying to solve, I'd do the following:
虽然一般电话号码验证是一个比您要解决的问题更大的问题,但我会执行以下操作:
var targ=phone_number_to_validate.replace(/[^\d]/g,''); // remove all non-digits
if(targ && targ.length===10) {
// targ is a valid phone number
}
Doing it this way will validate all of the following forms:
这样做将验证以下所有形式:
xxxxxxxxxx
xxx-xxx-xxxx
(xxx) xxx-xxxx
etc.
Also, to trivially check for a valid U.S. area code, you can use:
此外,要简单地检查有效的美国区号,您可以使用:
if(targ.matches(/^[2-9]\d{2}/)) // targ is a valid area code
Again, this is a trivial check. For something a little more rigorous, see this List of Legal US Area Codes.
同样,这是一个微不足道的检查。对于更严格的内容,请参阅此美国合法区号列表。
See also A comprehensive regex for phone number validation
另请参阅电话号码验证的综合正则表达式
回答by Pank
Use this :
用这个 :
/^(1-?)?(([2-9]\d{2})|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/
/^(1-?)?(([2-9]\d{2})|[2-9]\d{2})-?[2-9]\d{2}-?\d{ 4}$/
回答by kennebec
var rx=/^\d{3}\-?\d{3}\-?\d{4}$/;
if(rx.test(string)){
//10 diget number with possible area and exhange hyphens
}
else //not
回答by Rob Raisch
The following regular expression can be used to validate defined and operational (as of 6/2011) telephone area codes within the U.S.:
以下正则表达式可用于验证美国境内定义的和可操作的(截至 6/2011)电话区号:
var area_code_RE=
'(2(?:0[1-35-9]|1[02-9]|2[4589]|3[1469]|4[08]|5[1-46]|6[0279]|7[068]|8[13])'+
'|3(?:0[1-57-9]|1[02-9]|2[0139]|3[014679]|47|5[12]|6[019]|8[056])'+
'|4(?:0[126-9]|1[02-579]|2[3-5]|3[0245]|4[023]|6[49]|7[0589]|8[04])'+
'|5(?:0[1-57-9]|1[0235-8]|[23]0|4[01]|5[179]|6[1-47]|7[01234]|8[056])'+
'|6(?:0[1-35-9]|1[024-9]|2[0368]|3[016]|4[16]|5[01]|6[012]|7[89]|8[29])'+
'|7(?:0[1-4678]|1[2-9]|2[047]|3[1247]|4[07]|5[47]|6[02359]|7[02-59]|8[156])'+
'|8(?:0[1-8]|1[02-8]|28|3[0-25]|4[3578]|5[06-9]|6[02-5]|7[028])'+
'|9(?:0[1346-9]|1[02-9]|2[0578]|3[15679]|4[0179]|5[124679]|7[1-35689]|8[0459])'+
')';