使用JQuery Validate查看是否检查了至少一组radiobuttons

时间:2013-04-29 22:39:21

标签: jquery jquery-validate

有一个简单的表格。我需要验证至少其中一个联系人已选中本地单选按钮是。如何使用JQ Validate ??

这是小提琴

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"
        }
         }
     });
 });

3 个答案:

答案 0 :(得分:1)

嗯,页面上只有一个元素可以具有相同的IF。你可以试试这样的东西

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
}

答案 1 :(得分:1)

这里有一个小技巧,我不知道它是否最佳但是有效。

我的输入type='text'对于眼睛是不可见的,但不是display: none;

我添加了一个名称并创建了自定义验证:

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/

答案 2 :(得分:0)

我认为这就是你要找的东西:

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