使用validatedObservable的ko.validation给了我奇怪的结果

Bro*_*ato 3 knockout.js knockout-validation

我使用ko.validation检查我的页面上的有效数据,如下所示:

var postcode = ko.observable(),
    name = ko.observable();

var validationModel = ko.validatedObservable({
    postcode: postcode.extend({ required: true }),
    name: name.extend({ required: true })
});
Run Code Online (Sandbox Code Playgroud)

然后在我的确定按钮中,我在提交之前检查验证:

var buttonOk = function () {

    if (!validationModel.isValid()) {
        validationModel.errors.showAllMessages();
        return false;
    }
    ...
Run Code Online (Sandbox Code Playgroud)

它工作得很好:如果用户没有为邮政编码输入内容并且命名验证失败.

现在我添加了一些验证规则:

postcodeMustNotAlreadyExists + denominationMustNotAlreadyExists如下:

var validationModel = ko.validatedObservable({
    postcode: postcode.extend({ required: true }),
    name: name.extend({ required: true })
}).extend({
    postcodeMustNotAlreadyExists: cities,
    denominationMustNotAlreadyExists: cities
});

ko.validation.rules['postcodeMustNotAlreadyExists'] = {
    validator: function (val, cities) {
        // Try to find a match between the typed postcode and the postcode in the list of cities
        var match = ko.utils.arrayFirst(cities(), function (item) {
            return (val.postcode() === item.postCode());
        });            
        return !match;
    },
    message: 'This postcode already exists!'
};
ko.validation.rules['denominationMustNotAlreadyExists'] = {
    validator: function (val, cities) {
        // Try to find a match between the typed denomination and the denomination in the list of cities
        var match = ko.utils.arrayFirst(cities(), function (item) {
            return (val.name() === item.name());
        });
        return !match;
    },
    message: 'This denomination already exists!'
};
ko.validation.registerExtenders();
Run Code Online (Sandbox Code Playgroud)

validationModel.isValid()当用户没有为邮政编码或名称键入任何内容时,现在返回true.我注意到这validationModel().postcode.isValid()是错误的,因此将validationModel.isValid()设置为True并不是逻辑.

现在有了我的新实现,我必须测试两件事: (!validationModel.isValid() || validationModel().errors().length>0)

任何的想法?

谢谢.

Tom*_*dee 7

尝试使用以下内容覆盖isValid()viewModel中的函数:

self.isValid = ko.computed(function () {
        return ko.validation.group(
            self,
            {
                observable: true,
                deep: true
            }).showAllMessages(true);
    }, self);
Run Code Online (Sandbox Code Playgroud)