jquery验证至少检查一个复选框

发布于 2024-09-06 01:17:05 字数 440 浏览 3 评论 0原文

我有这样的事情:

<form>
<input name='roles' type='checkbox' value='1' />
<input name='roles' type='checkbox' value='2' />
<input name='roles' type='checkbox' value='3' />
<input name='roles' type='checkbox' value='4' />
<input name='roles' type='checkbox' value='5' />
<input type='submit' value='submit' />
<form>

我想验证至少应该检查一个复选框(角色),是否可以使用 jquery.validate ?

I have something like this:

<form>
<input name='roles' type='checkbox' value='1' />
<input name='roles' type='checkbox' value='2' />
<input name='roles' type='checkbox' value='3' />
<input name='roles' type='checkbox' value='4' />
<input name='roles' type='checkbox' value='5' />
<input type='submit' value='submit' />
<form>

I would like to validate that at least one checkbox (roles) should be checked, is it possible with jquery.validate ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

于我来说 2024-09-13 01:17:05

示例来自 https://github.com/ffmike/jquery-validate

 <label for="spam_email">
     <input type="checkbox" class="checkbox" id="spam_email" value="email" name="spam[]" validate="required:true, minlength:2" /> Spam via E-Mail </label>
 <label for="spam_phone">
     <input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam[]" /> Spam via Phone </label>
 <label for="spam_mail">
     <input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam[]" /> Spam via Mail </label>
 <label for="spam[]" class="error">Please select at least two types of spam.</label>

仅使用 javascript 在标签中没有字段“验证”时相同:

$("#testform").validate({ 
    rules: { 
            "spam[]": { 
                    required: true, 
                    minlength: 1 
            } 
    }, 
    messages: { 
            "spam[]": "Please select at least two types of spam."
    } 
}); 

如果您需要不同的输入名称,则可以使用如下所示的内容:

<input type="hidden" name="spam" id="spam"/>
<label for="spam_phone">
    <input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam_phone" /> Spam via Phone</label>
<label for="spam_mail">
    <input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam_mail" /> Spam via Mail </label>

Javascript:

 $("#testform").validate({ 
    rules: { 
        spam: { 
            required: function (element) {
                var boxes = $('.checkbox');
                if (boxes.filter(':checked').length == 0) {
                    return true;
                }
                return false;
            },
            minlength: 1 
        } 
    }, 
    messages: { 
            spam: "Please select at least two types of spam."
    } 
}); 

我在输入之前添加了隐藏输入,如果没有选择,则将其设置为“必需”复选框

Example from https://github.com/ffmike/jquery-validate

 <label for="spam_email">
     <input type="checkbox" class="checkbox" id="spam_email" value="email" name="spam[]" validate="required:true, minlength:2" /> Spam via E-Mail </label>
 <label for="spam_phone">
     <input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam[]" /> Spam via Phone </label>
 <label for="spam_mail">
     <input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam[]" /> Spam via Mail </label>
 <label for="spam[]" class="error">Please select at least two types of spam.</label>

The same without field "validate" in tags only using javascript:

$("#testform").validate({ 
    rules: { 
            "spam[]": { 
                    required: true, 
                    minlength: 1 
            } 
    }, 
    messages: { 
            "spam[]": "Please select at least two types of spam."
    } 
}); 

And if you need different names for inputs, you can use somethig like this:

<input type="hidden" name="spam" id="spam"/>
<label for="spam_phone">
    <input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam_phone" /> Spam via Phone</label>
<label for="spam_mail">
    <input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam_mail" /> Spam via Mail </label>

Javascript:

 $("#testform").validate({ 
    rules: { 
        spam: { 
            required: function (element) {
                var boxes = $('.checkbox');
                if (boxes.filter(':checked').length == 0) {
                    return true;
                }
                return false;
            },
            minlength: 1 
        } 
    }, 
    messages: { 
            spam: "Please select at least two types of spam."
    } 
}); 

I have added hidden input before inputs and setting it to "required" if there is no selected checkboxes

一瞬间的火花 2024-09-13 01:17:05

验证插件只会验证当前/焦点元素。因此,您需要向验证器添加自定义规则以验证所有复选框。与上面的答案类似。

$.validator.addMethod("roles", function(value, elem, param) {
   return $(".roles:checkbox:checked").length > 0;
},"You must select at least one!");

而在元素上:

<input class='{roles: true}' name='roles' type='checkbox' value='1' />

此外,您可能会发现错误消息的显示还不够充分。
仅突出显示 1 个复选框并仅显示 1 条消息。如果您单击另一个单独的复选框,然后该复选框返回第二个复选框的有效值,则原始复选框仍被标记为无效,并且尽管表单有效,但仍会显示错误消息。
在这种情况下,我总是自行显示和隐藏错误。然后验证器只负责不提交表单。

您的另一个选择是编写一个函数,该函数将在单击复选框时将隐藏输入的值更改为“有效”,然后将验证规则附加到隐藏元素。虽然这只会在 onSubmit 事件中验证,但会在适当的时间显示和隐藏消息。这些是您可以与验证插件一起使用的唯一选项。

希望有帮助!

The validate plugin will only validate the current/focused element.Therefore you will need to add a custom rule to the validator to validate all the checkboxes. Similar to the answer above.

$.validator.addMethod("roles", function(value, elem, param) {
   return $(".roles:checkbox:checked").length > 0;
},"You must select at least one!");

And on the element:

<input class='{roles: true}' name='roles' type='checkbox' value='1' />

In addition, you will likely find the error message display, not quite sufficient.
Only 1 checkbox is highlighted and only 1 message displayed. If you click another separate checkbox, which then returns a valid for the second checkbox, the original one is still marked as invalid, and the error message is still displayed, despite the form being valid.
I have always resorted to just displaying and hiding the errors myself in this case.The validator then only takes care of not submitting the form.

The other option you have is to write a function that will change the value of a hidden input to be "valid" on the click of a checkbox and then attach the validation rule to the hidden element. This will only validate in the onSubmit event though, but will display and hide messages at the appropriate times. Those are about the only options that you can use with the validate plugin.

Hope that helps!

路还长,别太狂 2024-09-13 01:17:05

嗯,首先你的 id 属性必须是唯一的,你的代码很可能是

<form>
<input class='roles' name='roles' type='checkbox' value='1' />
<input class='roles' name='roles' type='checkbox' value='2' />
<input class='roles' name='roles' type='checkbox' value='3' />
<input class='roles' name='roles' type='checkbox' value='4' />
<input class='roles' name='roles' type='checkbox' value='5' />
<input type='submit' value='submit' />
</form>

对于你的问题:

if($('.roles:checkbox:checked').length == 0)
  // no checkbox checked, do something...
else
  // at least one checkbox checked...

但是,请记住 JavaScript 表单验证只是指示性的,所有验证都必须在服务器端完成。

Mmm first your id attributes must be unique, your code is likely to be

<form>
<input class='roles' name='roles' type='checkbox' value='1' />
<input class='roles' name='roles' type='checkbox' value='2' />
<input class='roles' name='roles' type='checkbox' value='3' />
<input class='roles' name='roles' type='checkbox' value='4' />
<input class='roles' name='roles' type='checkbox' value='5' />
<input type='submit' value='submit' />
</form>

For your problem :

if($('.roles:checkbox:checked').length == 0)
  // no checkbox checked, do something...
else
  // at least one checkbox checked...

BUT, remember that a JavaScript form validation is only indicative, all validations MUST be done server-side.

清泪尽 2024-09-13 01:17:05
$("#idform").validate({
    rules: {            
        'roles': {
            required: true,
        },
    },
    messages: {            
        'roles': {
            required: "One Option please",
        },
    }
});
$("#idform").validate({
    rules: {            
        'roles': {
            required: true,
        },
    },
    messages: {            
        'roles': {
            required: "One Option please",
        },
    }
});
淡淡绿茶香 2024-09-13 01:17:05

这就是我过去处理这个问题的方法:

$().ready(function() {                                                      
    $("#contact").validate({
        submitHandler: function(form) {
            // see if selectone is even being used
            var boxes = $('.selectone:checkbox');
            if(boxes.length > 0) {
                if( $('.selectone:checkbox:checked').length < 1) {
                    alert('Please select at least one checkbox');
                    boxes[0].focus();
                    return false;
                }
            }
            form.submit();
        }
    }); 

});

This is how I have dealt with it in the past:

$().ready(function() {                                                      
    $("#contact").validate({
        submitHandler: function(form) {
            // see if selectone is even being used
            var boxes = $('.selectone:checkbox');
            if(boxes.length > 0) {
                if( $('.selectone:checkbox:checked').length < 1) {
                    alert('Please select at least one checkbox');
                    boxes[0].focus();
                    return false;
                }
            }
            form.submit();
        }
    }); 

});
客…行舟 2024-09-13 01:17:05

sir_neanderthal 已经发布了一个很好的答案。

我只是想指出,如果您想为输入使用不同的名称,您也可以使用(或只是复制方法)require_from_group 方法 来自官方 jQuery 验证additional-methods.js (链接到版本 1.13.1 的 CDN)。

sir_neanderthal has already posted a nice answer.

I just want to point out that if you would like to use different names for your inputs you can also use (or just copy the method) require_from_group method from official jQuery Validation additional-methods.js (link to CDN for version 1.13.1).

坚持沉默 2024-09-13 01:17:05

您很可能希望在复选框旁边有一个文本。在这种情况下,您可以将复选框放在标签内,如下所示:

<label style="width: 150px;"><input type="checkbox" name="damageTypeItems" value="72" aria-required="true" class="error"> All Over</label>
<label style="width: 150px;"><input type="checkbox" name="damageTypeItems" value="73" aria-required="true" class="error"> All Over X2</label>

问题是,当显示错误消息时,它将被插入到复选框之后、文本之前,从而使其不可读。为了解决这个问题,我更改了错误放置函数:

if (element.is(":checkbox")) {
    error.insertAfter(element.parent().parent());
}
else {
    error.insertAfter(element);
}

这取决于您的布局,但我所做的是为复选框控件设置特殊的错误放置。我得到了复选框的父级,这是一个标签,然后我得到了它的父级,在我的例子中是一个 div。这样,错误就会被放置在复选框控件列表的下方。

It's highly probable that you want to have a text next to the checkbox. In that case, you can put the checkbox inside a label like I do below:

<label style="width: 150px;"><input type="checkbox" name="damageTypeItems" value="72" aria-required="true" class="error"> All Over</label>
<label style="width: 150px;"><input type="checkbox" name="damageTypeItems" value="73" aria-required="true" class="error"> All Over X2</label>

The problem is that when the error message is displayed, it's going to be inserted after the checkbox but before the text, making it unreadable. In order to fix that, I changed the error placement function:

if (element.is(":checkbox")) {
    error.insertAfter(element.parent().parent());
}
else {
    error.insertAfter(element);
}

It depends on your layout but what I did is to have a special error placement for checkbox controls. I get the parent of the checkbox, which is a label, and then I get the parent of it, which is a div in my case. This way, the error is placed below the list of checkbox controls.

遥远的绿洲 2024-09-13 01:17:05

确保规则集中的 input-name[] 使用引号。我花了几个小时才弄清楚那部分。

$('#testform').validate({
  rules : {
    "name[]": { required: true, minlength: 1 }
  }
});

在这里阅读更多...
http://docs.jquery.com/Plugins/Valid...ets .2C_dots.29

make sure the input-name[] is in inverted commas in the ruleset. Took me hours to figure that part out.

$('#testform').validate({
  rules : {
    "name[]": { required: true, minlength: 1 }
  }
});

read more here...
http://docs.jquery.com/Plugins/Valid...ets.2C_dots.29

差↓一点笑了 2024-09-13 01:17:05
 if ($('input:checkbox').filter(':checked').length < 1){
        alert("Check at least one!");
 return false;
 }
 if ($('input:checkbox').filter(':checked').length < 1){
        alert("Check at least one!");
 return false;
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文