Skip to content

Custom Validation Rules

4Stern edited this page Mar 23, 2017 · 6 revisions

Custom Rules

Custom Rules can be created using the simple example below. All you need is to define a validator function and a default message. The validator function takes in the observable's value, and the params that you pass in with the extend method.

ko.validation.rules['mustEqual'] = {
    validator: function (val, otherVal) {
        return val === otherVal;
    },
    message: 'The field must equal {0}'
};
ko.validation.registerExtenders();

//the value '5' is the second arg ('otherVal') that is passed to the validator
var myCustomObj = ko.observable().extend({ mustEqual: 5 });

All Validation Messages can be formatted to use the passed in params to produce a custom message. message: 'The field must equal {0}' will be formatted with the 5 during actual validation so the user sees: 'The field must equal 5'.

You don't have to explicitly call registerExtenders() unless you initialize Validation with registerExtenders option set to false.

'Anonymous' or Single-Use Custom Rules

Anonymous rules are validation rules that are usually specific to only one object and might be determined on the fly.

var testObj = ko.observable(3).extend({
        validation: {
            validator: function (val, someOtherVal) {
                return val === someOtherVal;
            },
            message: 'Must Equal 5',
            params: 5
        }
    });

You can supply a validator or an array of them.

var testObj = ko.observable(3).extend({
        validation: [{
            validator: function (val, someOtherVal) {
                return val === someOtherVal;
            },
            message: 'Must Equal 5',
            params: 5
        },{
            validator: function (val) {
                return val !== 8;
            },
            message: 'Can not be 8',
        }]
    });