forked from Knockout-Contrib/Knockout-Validation
-
Notifications
You must be signed in to change notification settings - Fork 32
User Contributed Rules
fazzamar edited this page Sep 4, 2012
·
20 revisions
###Please feel free to contribute your own Custom Rules!###
####Example Rule####
ko.validation.rules['exampleRule'] = {
validator: function(val, otherVal){
/* awesome logic */
},
message: 'Sorry Chief, {0} this is not Valid'
};
####Change Limit Rule####
/**
* Limits the maximum amount a numeric value can be changed.
* Parameters: maxChange: <The max valid value change from base value>,
* baseValueAccessor: <A function to access the base value>
*
* Example: 'Distance can change a maximum of 10'
* var initDistance = 5;
* this.distance.extend({
* changeLimit:{
* maxChange:10,
* baseValueAccessor:function () {
* return initDistance;
* }
* }
* });
*
*/
ko.validation.rules['changeLimit'] = {
validator: function(val, options) {
return Math.abs(val - options.baseValueAccessor()) <= options.maxChange;
},
message: 'Change limit exeeded'
};
####Valid Object####
/*
* Aggregate validation of all the validated properties within an object
* Parameter: true|false
* Example:
*
* viewModel = {
* person: ko.observable({
* name: ko.observable().extend({ required: true }),
* age: ko.observable().extend({ min: 0, max: 120 })
* }.extend({ validObject: true })
* }
*/
ko.validation.rules["validObject"] = {
validator: function (obj, bool) {
if (!obj || typeof obj !== "object") {
throw "[validObject] Parameter must be an object";
}
return bool === (ko.validation.group(obj)().length === 0);
},
message: "Every property of the object must validate to '{0}'"
};
####Valid Array####
/*
* Aggregate validation of all the validated elements within an array
* Parameter: true|false
* Example
*
* viewModel = {
* person: ko.observableArray([{
* name: ko.observable().extend({ required: true }),
* age: ko.observable().extend({ min: 0, max: 120 })
* }, {
* name: ko.observable().extend({ required: true }),
* age: ko.observable().extend({ min:0, max:120 })
* }].extend({ validArray: true })
* }
*/
ko.validation.rules["validArray"] = {
validator: function (arr, bool) {
if (!arr || typeof arr !== "object" || !(arr instanceof Array)) {
throw "[validArray] Parameter must be an array";
}
return bool === (arr.filter(function (element) {
return ko.validation.group(ko.utils.unwrapObservable(element))().length !== 0;
}).length === 0);
},
message: "Every element in the array must validate to '{0}'"
};