2013-04-29 59 views
0

有一個簡單的表單。我需要驗證至少有一個聯繫人已經選中本地單選按鈕是。我如何用JQ驗證?使用jQuery驗證是否至少檢查一組單選按鈕是

這裏是小提琴

http://jsfiddle.net/davetoolin/dGsQR/1/

下面是HTML

<form id="contact" method="post" action="#"> 
<fieldset>Contact 1 
    <input class="name" id="name1" type="text" name="name1" size="20" maxlength=30> 
    <br>Local: 
    <input class="local" id="local1" type="radio" name="local1" Value="Y">Yes 
    <input class="local" id="local1" type="radio" name="local1" Value="N">No 
    <p>Contact 2 
     <input class="name" id="name2" type="text" name="name2" size="20" maxlength=30> 
     <br>Local 
     <input class="local" id="local2" type="radio" name="local2 " Value="Y ">Yes 
     <input class="local" id="local2" type="radio" name="local2 " Value="N ">No 
     <p>Contact 3 
      <input class="name" id="name3" type="text" name="name3" size="20" maxlength=30> 
      <br>Local 
      <input class="local" id="local3" type="radio" name="local3 " Value="Y ">Yes 
      <input class="local" id="local3" type="radio" name="local3 " Value="N ">No 
      <P> 
       <input type="submit" /> 
</fieldset> 

而且JS

$('#submit').click(function() { 
$('#mailer').submit(); 
return false; 
}); 
$(document).ready(function() { 

$("#contact").validate({ 
    rules: { 
     name1: { 
      required: true 
     }, 
     local1: { 
      required: function(element) { 
      return $('.local:checked').val() == "Y"; 
     } 
     messages: { 
      name1: { 
       required: "Name Required" 
      }, 
     local1: { 
      required: "At least one contact must be local" 
     } 
     } 
    }); 
}); 

回答

1

這裏有一個小竅門,我不知道它是否是最佳的,但它的工作。

我爲眼睛看不見,但不是display: none;

我加了一個名字並創建了一個自定義的驗證輸入type='text'

jQuery.validator.addMethod('checkLocal', function(value, element){ 
    var formValid = false 
    $('.local:checked').each(function(){ 
     if($(this).val() == "Y")formValid = true; 
    }) 
    return formValid; 
}, 'Please check something') 

添加在HTML那裏我想要的錯誤,顯示輸入並在此輸入上創建規則:

'checkError':{'checkLocal' : true} 

然後,驗證工作!

加入小提琴作爲證明:http://jsfiddle.net/dGsQR/3/

+0

仍然消化這個,但你的小提琴是完美的。猜測檢查你需要的每個功能的所有按鈕,因此需要新的方法。 無論如何,單獨顯示該錯誤可能是正確的行爲。非常感謝您的幫助。 – davewhirlwind 2013-04-30 01:19:06

+0

工程很好,我猜我需要了解更多關於addMethod的信息。 – davewhirlwind 2013-04-30 01:35:15

+0

艾哈我想我需要了解更多關於驗證插件:P – 2013-04-30 01:36:20

0

我認爲」 s你在找什麼:

if($('.local:checked').val() == "Y"){ 
    //Form is valid 
} 
+0

我可以建立在一個自定義規則? – davewhirlwind 2013-04-29 23:06:54

+0

對不起,JQ validate插件有規則和消息。立即嘗試, – davewhirlwind 2013-04-29 23:18:51

+0

想想我有什麼,做一個其他anwser! – 2013-04-29 23:59:08

1

那麼,只有一個頁面上的元素可以有相同的ID。你可以嘗試這樣的事情

if (($("input[name='local1']:checked").length > 0) | ($("input[name='local2']:checked").length > 0) | ($("input[name='local1']:checked").length > 0)){ 
    // one ore more checkboxes are checked 
} 
else{ 
// no checkboxes are checked 
}