0

我有一个带有一组复选框的表单字段,并且必须选择多个复选框中的至少一个才能提交表单。

我如何使用 YUI3 规则来实现这一点?

非常感谢,

rules: {
    fname: {
        required: true,
    },
    email: {
        required: true,
        email: true
    },
    tel: {
        required: true,
        digits: true,
    },
    dob: {
        date: true,
    },
},
fieldContainer: '.form__item',
containerErrorClass: 'form__item--error',

HTML:

<fieldset class="form__item form__item--group">
    <legend class="form__item__label">
        A group of checkboxes
        <div class="form__item__label__instructions">
            Select one of them.
        </div>
    </legend>

    <input name='errorMessageAnchor' hidden/>

    <label class="form__item__label" for="cb1">
        <input id="cb1" name="cbName" type="checkbox" class="checkbox" /> One
    </label>
    <label class="form__item__label" for="cb2">
        <input id="cb2" name="cbName" type="checkbox" class="checkbox" /> Two
    </label>
    <label class="form__item__label" for="cb3">
        <input id="cb3" name="cbName" type="checkbox" class="checkbox" /> Three
    </label>
    <label class="form__item__label" for="cb4">
        <input id="cb4" name="cbName" type="checkbox" class="checkbox" /> Four
    </label>
</fieldset>
4

1 回答 1

0

查看 aui-form-validator的源代码,使用 mix指示如何处理解决方案。

为简单起见,我还包含了 的用法gallery-checkboxgroups,专门用于CheckboxGroup以访问allUnchecked功能。

HTML

<form id="myForm">
 <div class="control-group">

    <div>
        <h5>Checkbox Group (requries at least 1 selection)</h5>

        Checkbox 1<input type='checkbox' class='checkbox' name='cbName'/><br/> 
        Checkbox 2<input type='checkbox' class='checkbox' name='cbName'/><br/>
        Checkbox 3<input type='checkbox' class='checkbox' name='cbName'/> 
    </div>
</div>
<input class="btn btn-info" type="button" value="Submit"/>

JS

YUI().use('aui-form-validator', 
          'gallery-checkboxgroups',
           function(Y) {

             var group = new Y.CheckboxGroup(Y.all('.checkbox'))

             var CONFIG = Y.config.FormValidator;
             Y.mix(CONFIG.RULES, {atLeastOneCheckbox: function(val, fieldNode, ruleValue) {
                    return !group.allUnchecked()
                }});

             var validator = new Y.FormValidator(
                    {
                        boundingBox: '#myForm',
                        rules: {
                            cbName:{custom:true, atLeastOneCheckbox:true}
                        }
                    }
            );

        }
);

小提琴


覆盖默认错误消息

 Y.mix(CONFIG.STRINGS,{atLeastOneCheckbox:"Pick at least 1"});

默认情况下,表单验证器将进行验证onBlur,并且由于所有复选框共享相同name的 ,错误消息将分别移动到最后一个“失败”验证字段。要解决此问题,请在组上方放置一个隐藏字段,并通过替换规则<input name='errorMessageAnchor' hidden/>将错误与该字段相关联cbName

errorMessageAnchor:{custom:true, atLeastOneCheckbox:true}
于 2014-08-14T14:48:22.300 回答