Useful Knockout JS Validation Rules

Knockout validation is an excellent starting point for adding validation rules to your apps. This is my collection of extra rules I add to my projects to fill in some gaps in the base.

//kind of like the min/max rule, but in some cases you just want a value greater than and not inclusive like min/max are
ko.validation.rules.greaterThan = {
    validator: function (val, otherVal) {
        return val > otherVal;
    },
    message: "The field must be greater than {0}"
};
//make sure entered value is a valid year (in the current millennium, not useful for ancient dates)
ko.validation.rules.year = {
    validator: function (val) {
        return /^\d{4}$/.test(val);
    },
    message: "Please enter a valid year"
};
//validate US phone numbers, pairs well with http://digitalbush.com/projects/masked-input-plugin
ko.validation.rules.phoneNumber = {
    validator: function (val) {
        return val === null || val === "" || val === "(___) ___-____" || /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/.test(val);
    },
    message: "Please enter a valid phone number"
};
//allows regexp to be optional
ko.validation.rules.optionalPattern = {
    validator: function (val, params) {
        return val === null || val === "" || params.test(val);
    },
    message: "Please enter a valid value"
};
//helpful when you need to make sure a checkbox or radio button has a specific value (aka required checkbox)
ko.validation.rules.checked = {
    validator: function (val) {
        if (!val) {
            return false;
        }
        return true;
    }
};
//Require observable arrays to be a certain length
ko.validation.rules.minArrayLength = {
    validator: function (arr, params) {
        if (!arr || typeof arr !== "object" || !(arr instanceof Array)) {
            throw "[validArray] Parameter must be an array";
        }
        if (params.required !== undefined) {
            return params.required ? arr.length >= params.length : params.required;
        } else {
            return arr.length >= params;
        }
    }
};

And of course, make sure you register the new rules!

ko.validation.registerExtenders();