我在一些网站上找到了这个代码,它工作得很完美。它验证电话号码是以下格式之一: (123) 456-7890或123-456-7890

问题是我的客户端(我不知道为什么,可能是客户端)想要添加另一种格式,连续的十个数字,像这样:1234567890。

我用这个正则表达式,

/^(\()?\d{3}(\))?(-|\s)?\d{3}(-|\s)\d{4}$/

我如何添加它也验证另一种格式?我不擅长使用正则表达式。


当前回答

我使用了@marty提供的一个,并对它进行了一些修改,以适应更多的情况:

/^[\+]?([0-9][\s]?|[0-9]?)([(][0-9]{3}[)][\s]?|[0-9]{3}[-\s\.]?)[0-9]{3}[-\s\.]?[0-9]{4,6}$/im

有效的格式:

+1 123 4567890 + 11234567890 + 1 (123)4567890 + 1 (123)456-7890 +1 (123) 456-7890 +1 (123)456 7890 +1 123 456-7890 +1 123 456 7890 +1 123-456-7890 The 123-456-7890 123 456-7890 123 456 7890 123 4567890 1234567890

其他回答

试试这个js函数。 如果匹配则返回true,如果失败则返回false 裁判

函数ValidatePhoneNumber(电话){ 返回/ ^ \ + ?([0 - 9]{2})\)?(-。] ?([0 - 9]{4})[-。] ?([0 - 9]{4})美元/ test(电话); }

一个很简单的方法:

"9001234567".match(/^\d{10}$/g)

我选择的正则表达式是:

/^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im

有效的格式:

(123) 456-7890 (123)456-7890 The 123-456-7890 123.456.7890 1234567890 + 31636363634 075-63546725

只是想添加一个解决方案,专门选择非本地电话号码(800和900类型)。

(\+?1[-.(\s]?|\()?(900|8(0|4|5|6|7|8)\3+)[)\s]?[-.\s]?\d{3}[-.\s]?\d{4}

除了数字,什么都不用管。

以下是我使用的方法:

// USA phones should contain at least 10 digits. For Ukrainian phones it's OK to have only 9 digits, without leading 0 and country code prefix: [+380] 88 888-88-88.
String.prototype.isValidPhone = function(digitsCount) {
  var str = this.trim().match(/\d/g);
  return str && str.length >= (digitsCount || 10); // default is at least 10 digits
}