Common Validation

by Alexander

JavaScript

/**** commonValidation.js ****/
(function () {
    window.commonValidation = {};
    
    Object.prototype.addRules = function(rules) {
        console.log("adding rules: " + JSON.stringify(rules) + " to " + JSON.stringify(this));
    };
    
    Object.prototype.validation = {};
    
    // Property used to store the rules that have been defined for the given property
    Object.prototype.validation.rules = {};
    
    Object.prototype.isValid = function() {
        // TODO: Iterate through this.validation.rules checking each
        // rule to see whether any return false; break on first error.
        return true;
    };
    
    Object.prototype.validation.getErrors = function() {
        if (this.isValid()) {
            return null;
        }
        // TODO: Iterate through every rule on the object and get the error messages for each property/rule.
        var errors = [];
        return errors;
    };

    commonValidation.rules = {};
    
    // Defining a built-in rule.
    commonValidation.rules["required"] = {
        validator: function (val, required) {
            var testVal;

            if (val === undefined || val === null) {
                return !required;
            }

            testVal = val;
            if (typeof (val) === "string") {
                if (String.prototype.trim) {
                    testVal = val.trim();
                } else {
                    testVal = val.replace(/^\s+|\s+$/g, "");
                }
            }

            // if they passed: { required: false }, then don't require this
            if (!required) {
                return true;
            }

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

/**** Some file that initializes the app ****/

// Defining a custom rule.
commonValidation.rules["mustEqual"] = {
    validator: function (val, otherVal) {
        return val === otherVal;
    },
    message: 'The field must equal...