敲除验证不显示选择倍数的错误消息

时间:2014-04-30 03:03:52

标签: javascript knockout.js knockout-validation

我设置了一个带有敲除验证插件的页面,用于验证用户输入。我有两个元素:一个是常规select,另一个是selectmultiple设置。我们的想法是使两个元素都是必需的。

验证调用正在触发,但问题是选择倍的错误消息未显示。

这是我的js代码:

  ko.validation.init();

    function isNotUndefined(val) {
        return (typeof val != "undefined");
    }

    function isArrayNotEmpty(val) {
        return (val.length > 0);
    }

    var viewModel = function () {
        var self = this;

        self.memberType = ko.observable().extend({
            validation: {validator: isNotUndefined, message:'Please select gender'}
        });
        self.seekingTypes = ko.observableArray().extend({
            validation: {validator: isArrayNotEmpty, message:'At least one option is required'}
        });
        self.memberTypeSource = [
            { id: 1, text: 'Man' },
            { id: 2, text: 'Woman' }
        ];
        self.errors = ko.validation.group(self);
        self.doValidation = function () {
            console.log('error count=' + self.errors().length);
            if (self.errors().length == 0) {
                console.log('Yay.');
            } else {
                self.errors.showAllMessages(true);
            }
        };

        return {
            memberType: self.memberType,
            seekingTypes: self.seekingTypes,
            memberTypeSource: self.memberTypeSource,
            errors: self.errors,
            doValidation: self.doValidation,

        }
    };

    addEventListener('load', function () {
        ko.applyBindings(viewModel);
    });

这是html:

Gender: <select data-bind="value: memberType,
                    options: memberTypeSource,
                    optionsText: 'text',
                    optionsValue: 'id',
                    optionsCaption: 'Please select'"></select>
<br />
Seeking: <select data-bind="selectedOptions: seekingTypes,
                    options: memberTypeSource,
                    optionsText: 'text',
                    optionsValue: 'id'"
                 multiple></select>
<br />

<button type="button" data-bind='click: doValidation'>Submit</button>

我还使用输入文本元素测试了验证,错误消息显示正常。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:6)

验证插件仅修改valuechecked绑定,以使它们自动“验证”兼容。

因此,selectedOptions未自动验证,因此您需要在makeBindingHandlerValidatable之前使用selectedOptions致电ko.applyBindings,以便使您的多重选择符合验证效果:

ko.validation.makeBindingHandlerValidatable('selectedOptions');
ko.applyBindings(new viewModel);

演示JSFiddle

作为替代解决方案,您还可以选择validationCore(或单独范围内的validationMessage binding):

<select data-bind="selectedOptions: seekingTypes,
                    options: memberTypeSource,
                    optionsText: 'text',
                    optionsValue: 'id', validationCore: seekingTypes" 
                    multiple></select>

演示JSFiddle