5

考虑以下代码 -

var MyObjectModel = function(myObject){
var self = this;
self.myNumber1 = ko.observable(myObject.number1).trimmed();
self.myNumber2 = ko.observable(myObject.number2).trimmed();

我想扩展 myNumber1 和 myNumber2,以添加淘汰赛验证,这样如果两者都是空的,它就会抛出错误,并且如果其中一个有值则保持正常。

知道如何实现这一目标吗?

4

2 回答 2

9

您可以使用 ko.computed 创建一个函数,该函数检查是否至少设置了两个字段中的任何一个,并且 onlyIf 在验证中以有条件地执行验证。

var MyObjectModel = function (myObject) {
    var self = this;
    self.myNumber1 = ko.observable(myObject.number1);
    self.myNumber2 = ko.observable(myObject.number2);

    self.numbersHaveNoValue = ko.computed(function () {
        var value1 = self.myNumber1(), value2 = self.myNumber2();
        return !ko.validation.rules.required.validator(value1, true) &&
               !ko.validation.rules.required.validator(value2, true);
    });

    self.myNumber1.extend({ required: { onlyIf: self.numbersHaveNoValue }});
    self.myNumber2.extend({ required: { onlyIf: self.numbersHaveNoValue }});
}

我创建了一个小提琴:http: //jsfiddle.net/delixfe/aBytt/

于 2013-01-25T13:10:11.443 回答
2
var MyObjectModel = function(myObject) {
    var self = this;
    self.myNumber1 = ko.observable(myObject.number1).trimmed();
    self.myNumber2 = ko.observable(myObject.number2).trimmed();

    self.numberCount = ko.computed(function() {
        var count = 0;
        count += self.myNumber1() != '' ? 1 : 0;
        count += self.myNumber2() != '' ? 1 : 0;
        return count;
    }).extend({min:1});
}
于 2014-01-14T16:14:59.030 回答