0

Usually validations work independent with respective binded content, eg http://jsfiddle.net/supercool/JL26Z/53/

But I have two text boxes name1 & name2, as mentioned in fiddle, I need to do show validation is failed if following condition fails:

  • name1 is mandatory if name2 is not entered.
  • name2 is mandatory if name1 is not entered.
  • if name1 & name2 left empty i need to show error message i.e validations failed.

If I got you confused: in short I am looking for validations to pass if text is entered in any of the textboxes.

super cool
  • 6,003
  • 2
  • 30
  • 63
  • 1
    https://github.com/Knockout-Contrib/Knockout-Validation/wiki/Conditional-Validation –  Aug 11 '14 at 09:56
  • 1
    http://stackoverflow.com/questions/14331948/knockout-validation-of-two-interdependent-fields –  Aug 11 '14 at 09:57

1 Answers1

1

Do it like @delixfe suggested in another question here on SO:

var Phone = function () {
    var self = this;

    self.name1 = ko.observable("");
    self.name2 = ko.observable("");

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

    self.Validation = ko.validatedObservable([
        self.name1.extend({ required: { onlyIf: self.numbersHaveNoValue }}),
        self.name2.extend({ required: { onlyIf: self.numbersHaveNoValue }})
    ]);
}

see fiddle

Community
  • 1
  • 1