Skip to content

Conditional Validation

jbeall edited this page Oct 1, 2013 · 6 revisions

Sometimes you will have a viewmodel property that is only required in depending on some other circumstances. You can use the onlyIf parameter, which accepts a function, to specify when that field is required. The required validator will only be applied if the onlyIf function returns true.

For example, consider an address block that requires a state only if the country is "US".

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.