淘汰验证复选框列表必需的验证消息

时间:2014-02-16 01:39:50

标签: knockout.js checkboxlist knockout-validation

我正在尝试使用Knockout创建一个Checkbox List,并要求使用Knockout Validation检查至少一个Checkbox。

我遇到的问题是,如果没有选中复选框,则会多次显示所需的验证消息,每个选项一次。我该如何解决这个问题?

工作示例:http://jsfiddle.net/aaronhoffman/BtK3t/

HTML

<script id="koValidationCustomMessageTemplate" type="text/html">
    <em class="text-danger" data-bind="validationMessage: field"></em>
</script>

<div class="col-sm-5" data-bind="foreach: TheCheckboxListOptions">
    <div class="checkbox">
        <label>
            <input type="checkbox" data-bind="value: $data, checked: $root.TheCheckboxListSelectedValues" /><span data-bind="text: $data"></span>
        </label>
    </div>
</div>

和javascript

ko.validation.configure({
    registerExtenders: true,
    messagesOnModified: true,
    insertMessages: true,
    parseInputAttributes: true,
    messageTemplate: "koValidationCustomMessageTemplate"
});

var TheViewModel = {

    TheCheckboxListOptions: [
        "Option 1",
        "Option 2",
        "Option 3",
        "Option 4"
    ],

    TheCheckboxListSelectedValues: ko.observableArray().extend({
        required: { message: "At least one option is required." }
    }),

};


ko.applyBindings(TheViewModel);

2 个答案:

答案 0 :(得分:1)

敲除验证生成的错误集合只有一条错误消息。但是,因为observable绑定到一个控件数组,所以每个控件都会显示一次。您可以将验证消息模板自定义为星号或每个控件为空,然后在控件数组上方显示验证摘要。看到我修改过的小提琴。

http://jsfiddle.net/BtK3t/2/

<script id="koValidationCustomMessageTemplate" type="text/html">
    <span style="color: Red" data-bind="if: field.isModified() && !field.isValid()">*</span>
</script>

<ul data-bind="foreach: errors, visible: showValidationSummary"
    style="display: none; margin-left: 5px; text-align: left;">
    <li style="color: Red"><span data-bind="text: $data"></span></li>
</ul>

答案 1 :(得分:0)

对于这种类型的东西,我通常在提交之前使用jQuery验证来验证表单(回发或通过AJAX)。我编写了一个自定义的jQuery验证规则。这是一个例子:

$.validator.addMethod('required_checkbox', function(value, element) {
    var $module = $('#myCheckboxList');
    var checked = $module.find('input[type="checkbox"]:checked');
    if (checked.length === 0) {
        return false;
    } else {
        return true;
    }
});

$.validator.addClassRules('required-checkbox', { 'required_checkbox': true });

标记看起来像:

<ul id="myCheckboxList">
    <li><input type="checkbox" name="MyCheckboxes" class="required-checkbox" value="@myList.Id"></li>
    ....
</ul>

您可以在提交前在Knockout视图模型中执行以下操作来验证整个表单或其中的一部分:

$('form').validate();
相关问题