Javascript 仅当选中某些单选按钮时才进行jQuery验证
我的表格上有一点简单的验证:Javascript 仅当选中某些单选按钮时才进行jQuery验证,javascript,jquery,validation,Javascript,Jquery,Validation,我的表格上有一点简单的验证: <script type="text/javascript"> $(function() { $("#postform").validate({ rules: { post_title: "required"
<script type="text/javascript">
$(function()
{
$("#postform").validate({
rules: {
post_title: "required",
post_url: "required",
post_code: "required",
post_content: "required",
post_tags: "required"
}
});
});
</script>
$(函数()
{
$(“#postform”).validate({
规则:{
帖子标题:“必选”,
post_url:“必需”,
邮政编码:“必需”,
发布内容:“必需”,
post_标签:“必需”
}
});
});
但是,如果某些单选按钮在我选择它们时被隐藏,而没有被选中,我不想要求post_url或post_代码。e、 g.这是收音机:
<li><label for="r1"><input type="radio" name="post_category" id="r1" value="12" checked="checked" /> Share an Article</label></li>
<li><label for="r4"><input type="radio" name="post_category" id="r4" value="14" /> Share a Link</label></li>
<li><label for="r3"><input type="radio" name="post_category" id="r3" value="13" /> Share some Code</label></li
分享一篇文章
共享链接
共享一些代码您可以通过使用具有“depends”值的对象而不是验证对象的字符串“required”来进行条件验证,如下所示:
$("#postform").validate({
rules: {
post_title: "required",
post_url: {
required: {
depends: function() {
return $('input[name=post_category]:checked').val() == '14';
}
}
},
post_code: {
required: {
depends: function() {
return $('input[name=post_category]:checked').val() == '13';
}
}
},
post_content: "required",
post_tags: "required"
}
});
验证框架自动使用该函数检查是否应进行验证。如果函数返回true,它将进行验证,否则不会进行验证。在这种情况下,每个函数都会查找要检查的无线电设备,然后将该无线电设备的值与我们需要的值进行比较,以便进行必要的验证。为什么要多次设置更改处理程序?
$("#postform").validate({
rules: {
post_title: "required",
post_url: {
required: {
depends: function() {
return $('input[name=post_category]:checked').val() == '14';
}
}
},
post_code: {
required: {
depends: function() {
return $('input[name=post_category]:checked').val() == '13';
}
}
},
post_content: "required",
post_tags: "required"
}
});