jQuery validate - 用户必须选择YES radio(而不是no)才能继续

时间:2011-10-13 18:46:30

标签: jquery jquery-plugins jquery-validate

我想设置一个jQuery验证规则,要求检查YES(不是否),以便表单验证/提交。用户必须接受条款。如果用户选择“否”,则会收到错误消息,并且表单将不会生效。使用jquery validate plugin实现此目的的正确方法是什么?

<form id="myForm">
<input type="radio" name="terms" id="terms1" value="Yes!" class="required" title="Must accept terms to continue" /> Yes
<input type="radio" name="terms" id="terms2" value="No" class="required" title="Must accept terms to continue" /> No
</form>

$("#myForm").validate({ 

/*
Insert your awesome jquery validation code here. Free beer to whoever answers the question!
*/

}); 

这是一个工作示例: http://jsfiddle.net/ThcS8/1/

向能够提供解决方案甚至更好的例子的人致敬!如果您正在寻找相同的解决方案,请投票,以获得关注。谢谢大家!

请投票选出您最喜欢的解决方案!

4 个答案:

答案 0 :(得分:11)

我也有这个问题,并尝试过各种各样的事情,包括上面提到的解决方案。最后,我编写了一个自定义验证器方法来检查单选按钮中的所需值:

jQuery.validator.addMethod("requiredRadioValue", function(value, element, params) { 
    var selectedValue = $('input:radio[name=' + element.name + ']:checked').val(); 
    return (typeof(params) == 'array') ? (params.indexOf(selectedValue) != -1) : selectedValue == params;
}, "You must select the required option."); 

使用该方法,例如

signedcif: { requiredRadioValue: 'yes' }

允许的选项可以是数组或单个值。

希望这会有所帮助,我希望这不是最直接的方式,所以任何替代方案都会感激不尽!

答案 1 :(得分:2)

您应该从无输入无线电中删除所需,然后只需执行

$("form").validate(); 

这会初始化jquery验证。它会看到需要选择是,并且不会让表单提交,直到它为止。

答案 2 :(得分:1)

将值从true和false分别更改为1和0。并添加规则 为了

$('form').validate({
rules:{
    terms: {min:1}
},
messages:{
    terms: {min:'you must accept terms to move on.'}
}
});

答案 3 :(得分:1)

假设该复选框具有“必需”类并且名称为“agreeForm”,则可以使用以下内容:

   jQuery("#regForm").validate({
      debug: true,
      rules: {
        agreeForm: "required",
      },
      messages: {
        agreeForm: "Please accept our Terms and Conditions.",
      }
    });
相关问题