Skip to content

Conditional Validation

jbeall edited this page Jun 21, 2013 · 6 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); }
        }
    });