Skip to content

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'
};

####Required If True####

/*
* Makes the value required only if another value evaluates to true. 
* Useful for making a field required only if another field has text.
* Parameters: Function or value that if it returns/is true makes the value required.
* Example: 
*   viewModel = new function () {
*       var self = this;
*       this.IsEmployee = ko.observable(false);
*       this.EmployeeID = ko.observable().extend( { requiredIfTrue: self.IsEmployee });
*   };       
*/
ko.validation.rules['requiredIfTrue'] = {
    validator: function (val, otherVal) {
        var other = ko.validation.utils.getValue(otherVal),
            StringTrimRegEx = /^\s+|\s+$/g,
            testVal;
        // Test other val first, if it isn't true then val isn't required.
        if (other !== true) {
            return true;
        }
        // This is pulled right out of ko.validation's required rule (with minor editing)
        if (val === void (0) || val === null) {
            return false;
        }
        testVal = val;
        if (typeof (val) === "string") {
            testVal = val.replace(StringTrimRegEx, '');
        }

        return ((testVal + '').length > 0);
    },
    message: 'This field is required.'
};

####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}'"
};
Clone this wiki locally