[英]jQuery Validation ONLY when certain radio buttons selected
我在表單上有這個簡單的驗證:
<script type="text/javascript">
$(function()
{
$("#postform").validate({
rules: {
post_title: "required",
post_url: "required",
post_code: "required",
post_content: "required",
post_tags: "required"
}
});
});
</script>
但是如果沒有檢查某些單選按鈕,我不想要post_url或post_code,因為當我選擇它們時它們會被隱藏。 例如這里是收音機:
<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
然后這是隱藏或顯示它們的jquery代碼:
<script type="text/javascript">
jQuery(document).ready(function($)
{
$("input[name='post_category']").change(function()
{
$("#discussion-label").toggle(this.value == "12");
});
$("input[name='post_category']").change(function()
{
$("#code-container").toggle(this.value == "13");
$("#code-label").toggle(this.value == "13");
});
$("input[name='post_category']").change(function()
{
$("#link-container").toggle(this.value == "14");
$("#link-label").toggle(this.value == "14");
});
$("input#r1:checked").change();
$("input#r3:checked").change();
$("input#r4:checked").change();
});
</script>
因此,我們的想法是,當用戶選擇第一個單選按鈕時,只會驗證post_title,post_content和post_tags。 如果用戶選擇第二個單選按鈕,它也將驗證post_url字段,如果他們選擇第三個單選按鈕,則它將驗證post_code字段但不再是post_url,反之亦然。
有人可以幫忙嗎? 謝謝
您可以通過使用具有“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,它將驗證,否則不會。 在這種情況下,每個功能都是查找哪個無線電被檢查,然后將該無線電的值與我們需要的值進行比較,以便進行驗證。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.