Skip to content

Conditional Validation

Mehdi Mollaverdi edited this page Aug 26, 2013 · 6 revisions
ko.validation.init();

function Address() {
  var self = this;
  self.availableCountries= ['AU', 'NZ', 'US'];
  self.availableStates =  ['Alabama', 'Alaska', 'Arizona', 'Arkansas'];
  self.country = ko.observable().extend({required: true});
  //State is only required if 'US' is selected as country
  self.state = ko.observable().extend({required: {onlyIf:
    function() {return self.country() === 'US';}}});
};

var address = ko.validatedObservable(new Address())();
ko.applyBindings(address);

See the example here on jsFiddle.

Clone this wiki locally