Knockout Validation of two interdependent fields
Asked Answered
B

2

5

Consider the following piece of code -

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

I would like to extend myNumber1 and myNumber2, to add knockout validations such that it throws an error if both are empty, and stays fine if either has a value.

Any idea how I could go about achieving this ?

Blades answered 15/1, 2013 at 6:1 Comment(0)
S
9

You can use an ko.computed to create a function which checks if at least any of both fields is set and onlyIf in the validation to execute the validation conditionally.

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 }});
}

I have created a fiddle: http://jsfiddle.net/delixfe/aBytt/

Stellular answered 25/1, 2013 at 13:10 Comment(2)
i was hoping this was going to help me in my current problem, but the fiddle seems to be missingNixie
I am not sure, but I guess there's a mistake with using ...required.validator(value1, true) for both myNumber1 and myNumber2 validationMoscow
V
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});
}
Voter answered 14/1, 2014 at 16:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.