在验证observableArray of observable时,Knockout js验证插件问题

时间:2013-05-28 22:13:05

标签: knockout.js knockout-validation

我有一个可观察的observable数组 - 每个observable都已被扩展为require但是当我保存带有已清除字段的表单时,它不会收集错误或显示任何错误 -

ko.validation.configure({
    grouping: {
        deep: true,
        observable: true
    }
});


var viewModel = function () {
    var self = this;
    var data = {
        "deadzone": "0.2",
            "sloperange": "2",
            "stepsize": "0.8",
            "setpoint": "0.75",
            "pressure": "1"
    };
    self.defaultCalculations = ko.observableArray([]);
    self.defaultCalculationProperties = function (defaults) {
        var self = this;
        var properties = defaults;
        self.deadzone = ko.observable(properties.deadzone || '').extend({
            required: {
                message: '*required'
            }
        });
        self.sloperange = ko.observable(properties.sloperange || '').extend({
            required: {
                message: '*required'
            }
        });
        self.stepsize = ko.observable(properties.stepsize || '').extend({
            required: {
                message: '*required'
            }
        });
        self.setpoint = ko.observable(properties.setpoint || '').extend({
            required: {
                message: '*required'
            }
        });
        self.pressure = ko.observable(properties.pressure || '').extend({
            required: {
                message: '*required'
            }
        });

    };
    //populate calculation values
    self.populateCalculationDefaults = function (data) {

        //pushing data to an array and mapping each item
        var temp = [];
        temp[0] = data;
        var mappedTasks = _.map(temp, function (item) {
            return new self.defaultCalculationProperties(item);
        });

        self.defaultCalculations(mappedTasks);
    };

    self.save = function (model) {
        //console.log(model);
        console.log(self.errors().length, self.errors.showAllMessages());
        if (self.errors().length != 0) {
            self.errors.showAllMessages();
        }
    };
    self.errors = ko.validation.group(self.defaultCalculations());

    self.populateCalculationDefaults(data);
};

ko.applyBindings(new viewModel());

不确定问题是什么,已经扫过堆栈流 - 有什么建议吗?

http://jsfiddle.net/kmcadams/W2SZb/

2 个答案:

答案 0 :(得分:1)

最简单的事情是在populate函数中再次调用ko.validation.group。我更喜欢的另一个选择是订阅defaultcalculations并在那里运行组呼。

self.defaultCalculations.subscribe(function () {
    self.errors = ko.validation.group(self.defaultCalculations);
});

这将手动订阅要在任何时候运行的函数defaultCalculations有一个项目添加/删除。

答案 1 :(得分:0)

您还可以在扩展observable时始终添加notify。

this.validationModel = ko.validatedObservable({
    Num: ko.observable(this.Num).extend({ number: true, notify: 'always' }),
});

它对我有用。以前,当这个.Num没有被修改时,它没有被验证。