-
Notifications
You must be signed in to change notification settings - Fork 369
Custom Validation Rules
philjones edited this page May 18, 2012
·
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'
####'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
}
});