我正在使用RegExp来验证美国电话号码。对于ReEmailFormat6,我得到以下错误:
,但其他表达式运行良好。我不确定为什么是这个问题。请在下面找到我的代码:
var reEmailFormat2 = new RegExp("(.)\1{7,}"); //match if phone number has same number repeated 8 or more times
var reEmailFormat3 = new RegExp("^0{1}[\d]{9}$"); //match if phone number has leading 0 with 9 digits after the 0
var reEmailFormat4 = new RegExp("1{1}[\d]{9}$"); //match if phone number has leading 1 with 9 digits after the 1
var reEmailFormat5 = new RegExp("/^[+]?(1\-|1\s|1|\d{3}\-|\d{3}\s|)?((\(\d{3}\))|\d{3})(\-|\s)?(\d{3})(\-|\s)?(\d{4})$/g");
var reEmailFormat6 = new RegExp("^(?:\+?1[-. ]?)?\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$");
debugger;
if (controlToValidate[0].value == "" || controlToValidate[0].value == controlToValidate.attr("placeholder")) {
args.IsValid = false;
controlToValidate.addClass("site-validation-field");
}
else if (controlToValidate[0].value == "") {
args.IsValid = false;
controlToValidate.addClass("site-validation-field");
}
else if ((reEmailFormat6.test(controlToValidate[0].value))) {
debugger;
args.IsValid = false;
controlToValidate.addClass("site-validation-field");
}
答案 0 :(得分:1)
使用正则表达式文字语法重写所有正则表达式:
var reEmailFormat2 = /(.)\1{7,}/; //match if phone number has same number repeated 8 or more times
var reEmailFormat3 = /^0{1}[\d]{9}$/; //match if phone number has leading 0 with 9 digits after the 0
var reEmailFormat4 = /1{1}[\d]{9}$/; //match if phone number has leading 1 with 9 digits after the 1
var reEmailFormat5 = /^[+]?(1\-|1\s|1|\d{3}\-|\d{3}\s|)?((\(\d{3}\))|\d{3})(\-|\s)?(\d{3})(\-|\s)?(\d{4})$/g;
var reEmailFormat6 = /^(?:\+?1[-. ]?)?\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
当您将正则表达式形成为 strings 并传递给RegExp()
构造函数时,必须考虑到JavaScript中的字符串语法还将反斜杠字符用作元字符。因此,如果您不将源字符串中的反斜杠字符加倍,则将其解析为字符串的过程将删除。