您可以使用 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/