19

I am trying to use KnockoutValidation with conditional statements. See code below:

self.transactionType = ko.observable('Option1');

self.ConditionalField = ko.observable().extend({
  required: true, 
  onlyIf: self.transactionType = ="Option2"
});

Unfortunately this doesn't work. I want to have ConditionalField only required if transactionType has value 'Option2'.

What is the best way to use conditional validation with knockout.validation.js?

Tomalak
  • 332,285
  • 67
  • 532
  • 628
Mounhim
  • 1,674
  • 1
  • 17
  • 32

1 Answers1

39

I have solved it.

First of all I made the mistake of declaring the transactiontype after I had defined the conditionalfield. The end code that works looks like this:

self.transactionType = ko.observable("Option1");

self.conditionalField = ko.observable().extend({
  required: {
    onlyIf: function () { 
      return self.transactionType () == "Option2";
    }
  }
});
Tomalak
  • 332,285
  • 67
  • 532
  • 628
Mounhim
  • 1,674
  • 1
  • 17
  • 32
  • 8
    Well, it's been said Thomas Edison had 3000 failed attempts before he invented the first commercially practical incandescent light. http://en.wikipedia.org/wiki/Thomas_Edison#cite_note-28, but I find your answer to be just as illuminating... thanks & + 1 – James Fleming Jan 08 '13 at 13:39
  • 2
    Sadly this onlyIf stuff is not documented anywhere. Thanks! – Jason More Apr 03 '13 at 20:35
  • 2
    [onlyIf documentation](https://github.com/Knockout-Contrib/Knockout-Validation/wiki/Conditional-Validation-with-onlyIf-parameter) – Homer Dec 12 '13 at 20:59
  • Really useful. I appreciate you took the time to response your own answer. Thanks! – kerzek Feb 19 '14 at 17:57
  • Agreed! Still useful 3 years later! – Laura Ritchey Jul 20 '15 at 17:25