我正在使用jquery验证器,我在其中添加了一个方法来验证字符串,该字符串只允许数字,空格,加号,连字符和括号。数字在字符串中是必需的,但其他租约者是可选的。
我在jquery validor中添加方法的代码:
jQuery.validator.addMethod( "regex", function(value, element, regexp) {
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
"Please check your input."
);
遵循规则的代码:
rules: {
myfield: {
required: true,
regex: "[0-9]+" // want to add regular expression but I wrote only for digit which works but do not understand how to reach at my requirements.
},
}
答案 0 :(得分:34)
您可以将所需字符添加到字符类中
/^(?=.*[0-9])[- +()0-9]+$/
正则表达式解释
(?=.*[0-9])
正面向前看。确保至少有一位数
[- +()0-9]+
匹配数字,空格,加号,连字符和括号
或强>
如果您不愿意使用预测。你可以在没有它们的情况下写一个lenghier正则表达式
/^[- +()]*[0-9][- +()0-9]*$/