谁能告诉我如何编写一个规则来验证用户是否选择/填写了一个单选按钮选项和(可选)文本字段?如果未选择复选框选项 #myradiogroup
且文本字段 #email2
为空,则该规则应仅给出一条消息。
我的表单代码:
<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
参数可以接受一个函数。
$('#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();
}
}
}
});
关于javascript - 使用 jquery.validate.js 插件进行条件表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18897714/