1

我有下面的脚本,它检查以确保电话号码的表单字段包含 10 位数字、连字符和 ( ) 字符。我遇到的问题是很多时候人们会输入一个这样的电话号码 - 000 000 0000

当脚本被调用时,它会抛出一条错误消息。如何使用下面的脚本但允许指定格式 000 000 0000 的空格而不引发错误?

谢谢你的帮助!

              function validateTel(telnum) {
              if (telnum.match(/^(1?(-?\d{3})-?)?(\d{3})(-?\d{4})$/)) {
              return true;
              } else {
              return false;
              }
              }
4

2 回答 2

0

您可以使用此正则表达式来匹配电话号码

^\d{3}[ ]{0,1}\d{3}[ ]{0,1}\d{4}$

检查这里的解释http://regex101.com/r/iG2fV4

样本:

var telRegExp = /^\d{3}[ ]{0,1}\d{3}[ ]{0,1}\d{4}$/;

console.log("1234567890".match(telRegExp))
console.log("123 456 7890".match(telRegExp))
console.log("123 4567890".match(telRegExp))
console.log("123456 7890".match(telRegExp))
console.log("a1234567890".match(telRegExp))

输出

[ '1234567890', index: 0, input: '1234567890' ]
[ '123 456 7890', index: 0, input: '123 456 7890' ]
[ '123 4567890', index: 0, input: '123 4567890' ]
[ '123456 7890', index: 0, input: '123456 7890' ]
null
于 2013-10-26T09:02:35.557 回答
0

如何使用锚点?

/^\d{10}$/

或者可能是这个正则表达式: -

/^\+?\d{2}[- ]?\d{3}[- ]?\d{5}$/

或者可能是这个正则表达式,它将涵盖大多数情况以验证电话号码:

^(?:\+?\d{2}[ -]?\d{3}[ -]?\d{5}|\d{4})$

正则表达式演示

于 2013-10-26T09:02:35.640 回答