敲除验证两个相互依赖的字段

时间:2013-01-15 06:01:29

标签: javascript knockout.js knockout-validation

考虑以下代码 -

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

我想扩展myNumber1和myNumber2,添加敲除验证,如果两者都为空则抛出错误,如果有值,则保持正常。

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

2 个答案:

答案 0 :(得分:9)

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

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/

答案 1 :(得分: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});
}