如何使用YUI3 AlloyUI验证一组复选框?

时间:2014-08-13 13:48:09

标签: javascript yui yui3 alloy-ui

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

如何使用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>

1 个答案:

答案 0 :(得分:0)

查看source for aui-form-validatoruse of 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}
                        }
                    }
            );

        }
);

Fiddle


覆盖默认错误消息

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

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

errorMessageAnchor:{custom:true, atLeastOneCheckbox:true}