jQuery validate-如何使用两个XOR规则验证一个字段 [英] jQuery validate - how to validate one field with two XOR rules
问题描述
我有一个字段可以包含电子邮件或手机(在我的情况下,手机为8位数字). 我已经尝试了两种方法(两个示例都不起作用,因为元素"没有验证方法):
I have one field which can contain email or mobile (in my case mobile is 8 digits). I already tried two approaches (both examples doesn't work, because 'element' do not have validate method):
第一种方法:创建自定义方法并在此进行两个验证,但是然后我必须创建自己的电子邮件验证和移动验证-我找不到在新方法中重用jQuery验证规则的方法.这就是我想要的:
First approach: create custom method and do both validations there, but then I have to create my own email and mobile validation - I couldn't find a way how to reuse jQuery validation rules in new methods. This is what I'd like to have:
jQuery.validator.addMethod("mobileoremail", function(value, element) {
return this.optional(element) ||
element.validate({ rules: { digits: true, rangelength: [8, 8] } }) ||
element.validate({ rules: { email: true } });
}, "Invalid mobile or email");
第二种方法:创建依赖规则.而且在这种情况下,我也找不到如何重用jQuery验证规则的方法.
Second approach: create dependent rules. And also in this case I couldn't find a way how to reuse jQuery validation rules.
{ myRules: {
rules: {
user: {
required: true,
email: {
depends: function(element) {
return !element.validate({ rules: { mobile: true } });
}
},
mobile: {
depends: function (element) {
return !element.validate({ rules: { email: true } });
}
}
}
}
}
}
推荐答案
以下验证方法...
$.validator.addMethod("xor", function(val, el, param) {
var valid = false;
// loop through sets of nested rules
for(var i = 0; i < param.length; ++i) {
var setResult = true;
// loop through nested rules in the set
for(var x in param[i]) {
var result = $.validator.methods[x].call(this, val, el, param[i][x]);
// If the input breaks one rule in a set we stop and move
// to the next set...
if(!result) {
setResult = false;
break;
}
}
// If the value passes for one set we stop with a true result
if(setResult == true) {
valid = true;
break;
}
}
// Return the validation result
return this.optional(el) || valid;
}, "The value entered is invalid");
然后我们可以按照以下步骤设置表单验证...
Then we could set up the form validation as follows...
$("form").validate({
rules: {
input: {
xor: [{
digits: true,
rangelength: [8, 8]
}, {
email: true
}]
}
},
messages: {
input: {
xor: "Please enter a valid email or phone number"
}
}
});
在此处查看操作情况 http://jsfiddle.net/eJdBa/
这篇关于jQuery validate-如何使用两个XOR规则验证一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!