-
Notifications
You must be signed in to change notification settings - Fork 379
Override Error Messages
Cristian Trifan edited this page Jan 29, 2015
·
2 revisions
You can override the default message for a validation on a per property basis. Here is how you configure the extend call:
ko.validation.rules['mustEqual'] = {
validator: function(val, otherVal) {
return val === otherVal;
},
message: 'The field must equal {0}'
};
ko.validation.registerExtenders();
// If not modifying the default message, you would call like this:
// viewModel.PercentSum.extend({ mustEqual: 100 });
// If you want to override the message, you need to move
// your validation parameter into the "params" field
viewModel.PercentSum.extend({
mustEqual: {
params: 100,
message: "Percentages must add to 100"
}
});
Starting with version 2.0.0
the validation message can contain multiple placeholders {0}
. For instance, the following custom rule takes advantage of this feature.
ko.validation.rules.between = {
validator: function(value, params) {
var min = params[0];
var max = params[1];
value = parseInt(value, 10);
if (!isNaN(value)) {
return value >= min && value <= max;
}
return false;
},
message: 'Value must be between {0} and {1}'
};
ko.validation.registerExtenders();
// Use the rule
viewModel.someValue.extend({between: [10, 100]});