KnockoutValidation and the conditional required rule

Mounhim picture Mounhim · Jul 31, 2012 · Viewed 9k times · Source

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?

Answer

Mounhim picture Mounhim · Jul 31, 2012

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