使用jquery.validate.js插件进行条件表单验证 [英] conditional form validation using jquery.validate.js plugin
本文介绍了使用jquery.validate.js插件进行条件表单验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
谁能告诉我如何编写一条规则来验证用户是否选择/填充了一个单选按钮选项和(最佳)文本字段?仅当未选择复选框选项#myradiogroup
并且文本字段#email2
为空时,该规则才给出消息.
Can anyone tell me how to write a rule that validates if neither one radio button option nor the (optinal) textfield is chosen/filled by a user? The rule should only give a message if no checkbox option #myradiogroup
is chosen AND the textfield #email2
is empty.
我的表单代码:
<form name="my" id="myForm" action="" method="post">
<input type="radio" name="myradiogroup" id="myradiogroup" value="option 1" /> option 1
<input type="radio" name="myradiogroup" id="myradiogroup" value="option 2" /> option 2
<label for="emailNew4use">this is an optional field:</label>
<input type="text" name="email2" id="email2" />
<input type="submit" value="send">
</form>
推荐答案
jQuery Validate中的required
参数可以使用一个函数.
The required
parameter in jQuery Validate can take a function.
$('#myForm').validate({
rules: {
email2: {
required: function(element) {
if ($('[name="myradiogroup"]:checked').length) {
return false;
} else {
return true;
}
}
},
myradiogroup: {
required: function(element) {
if ($('#email2').val()) {
return false;
} else {
return true;
}
}
}
}
});
这是 Sparky
$('#myForm').validate({
rules: {
email2: {
required: function(element) {
return !$('[name="myradiogroup"]:checked').length;
}
},
myradiogroup: {
required: function(element) {
return !$('#email2').val();
}
}
}
});
这篇关于使用jquery.validate.js插件进行条件表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文