使用jQuery验证的第一天,但不是jQuery的第一天.很简单的问题:我有三个文本输入:姓名,电话和电子邮件.我想要名字(没有汗水)和EITHER手机或电子邮件,并确保输入在EITHER手机或电子邮件中有效.我试过这个:
$(document).ready(function() {
$("#contactForm").validate({
debug:true,
rules: {
name: {
required: true
},
email: {
email:true,
required: function(element){
!$("#phone").valid();
}
},
phone: {
phoneUS: true,
required: function(element){
!$("#email").valid();
}
}
},
messages: {
name: "Please specify your name",
email: {
required: "Please enter a valid email"
},
phone: "Please enter a 10 digit phone number"
}
});
});
但它失败了,因为每个有效性检查调用另一个,无限递归并崩溃浏览器.
必须有一些简单的方法来做到这一点,但我已经花了将近两个小时,它逃脱了我:(
最佳答案 您可以在使用后创建方法
创建方法:
$.validator.addMethod("eitherEmailPhone", function(value, element) {
isPhone = (this.optional(element) || /^\d+$/.test(value)) && this.getLength($.trim(value), element) <= 12 && this.getLength($.trim(value), element) >= 11 ;
isEmail = this.optional(element) || /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(value);
return isPhone || isEmail;
}, "Please enter either phone or e-mail");
现在你可以使用方法“yesEmailPhone”
对于multidata案例:
<input type="text" name="email_or_phone" class="{eitherEmailPhone:true}" value="" />
Where only digits allowed for phone format, so you can change it by your need