Messaging and Validators

by Renoir Boulanger

HTML

<script src="https://www.theinstitutes.org/cloudflare/underscore.js/1.3.3/underscore-min.js"></script>

JavaScript

/*!
 * Messageable functional "Part"
 *
 * Insert either an object, or a function into messageable(obj)
 * and adds message key/value store specific to the object.
 *
 * As described by Douglas Crockford's book: Javascript The Good Parts
 *
 * To use, only pass an object/function to messageable.
 *
 * <code>
 *   var hello = {
 *       // an object, or function
 *   };
 *
 *   messageable(hello);
 *
 *   if ( hello.messageable ) {
 *       hello.addMessage('hello', 'Hello world');
 *       hello.getMessage('hello'); // Hello world
 *   }
 * </code>
 *
 * @author Renoir Boulanger <[email protected]>
 **/
var messageable = function(that) {
    // require('underscore');

    var messages = [];

    that.messageable = true;

    function slugifyKey(keyName) {
        return keyName.toLowerCase();
    }

    that.hasMessage = function (keyName) {
        var k = slugifyKey(keyName),
            foundKey = _.where(messages, {key: k});

        if (foundKey.length === 0) {
            return false;
        }

        return true;
    };

    that.addMessage = function (keyName, message) {
        var k = slugifyKey(keyName),
            m = message;

        if (this.hasMessage(k)) {
            throw 'This key is already defined';
        }

        messages.push({key: k, message: m});
    };

    that.getMessage = function (keyName) {
        if (this.hasMessage(keyName)) {
            var k = slugifyKey(keyName),
                found = _.where(messages, {key: k});

            return found[0].message;
        }

        return null;
    };
};
/* /Messageable functional "Part" */




/**
 * Validator Data Transfer Object modifier
 *
 * Adds validation patterns list to an object
 *
 * NOTE: We should be using requirejs or commonjs to declare
 *       dependencies, in the meantime, it is comments, like below:
 *
 * Requires:
 *   - underscore
 *   - jQuery
 *
 * One private property 'patterns' should look like: [{key: (string), expect: (bool), pattern: (regex)}]
...