Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KnockoutValidation and the conditional required rule

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?

like image 812
Mounhim Avatar asked Jul 31 '12 11:07

Mounhim


1 Answers

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";
    }
  }
});
like image 147
Mounhim Avatar answered Nov 10 '22 01:11

Mounhim