Skip to content

Conditional Validation with onlyIf parameter

Cristian Trifan edited this page Jan 29, 2015 · 3 revisions

Sometimes you will have a viewmodel property that is only required in certain 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 postal code unless a "noPostalCode" field is set to true.

self.postalCode.extend({
    required: {
        message: "Postal Code is required",
        onlyIf: function() {
            return self.noPostalCode() === false;
        }
    }
});

See another example here on jsFiddle.

Conditional validation onlyIf can be used in combination with all other KO validation rules (e.g. max, min, etc.)