KnockoutValidation and the conditional required rule
Asked Answered
S

1

20

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?

Sopping answered 31/7, 2012 at 11:1 Comment(0)
S
40

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";
    }
  }
});
Sopping answered 31/7, 2012 at 11:18 Comment(5)
Well, it's been said Thomas Edison had 3000 failed attempts before he invented the first commercially practical incandescent light. en.wikipedia.org/wiki/Thomas_Edison#cite_note-28, but I find your answer to be just as illuminating... thanks & + 1Lori
Sadly this onlyIf stuff is not documented anywhere. Thanks!Pegues
onlyIf documentationUnblushing
Really useful. I appreciate you took the time to response your own answer. Thanks!Fillian
Agreed! Still useful 3 years later!Plow

© 2022 - 2024 — McMap. All rights reserved.