Validation Plugin

Plugin for the management of client-side validation.

by Troy Alford

HTML

<input id="TestTextbox" type="text" value="Text here" /><br />
<button id="TestButton" value="Validate" />

CSS

.validation-invalid {
    border: 1px solid red;
    background-color: #FF9999;
}

JavaScript

(function($) {

    var defaults = {

        automatic: true,
        enabled: true,
        msgs: [],
        // Msgs should be in the format { passed: true/false, msg: 'pass/fail message' }
        key: 'default',
        invalidCls: 'validation-invalid',

        //Default validation functions
        validate: function() {
            return true;
        }

    };

    var methods = {
        add: function(settings) {
            var options = $.extend(true, {}, defaults, settings);

            // 'this' may be multiple elements in a set.
            this.each(function() {
                var $target = $(this); // 'this' is now a single element
                var validators = $target.data('Validators');
                if (!validators) {
                    validators = {};
                }

                validators[options.key] = options;

                $target.data('Validators', validators).attr('Validatable', true);
            });

            return this; // Enable chaining
        },
        clear: function() {
            var $toClear = this.add(this.find('[Validatable]'));

            $toClear.each(function() {
                var $target = $(this); // 'this' is now a single element
                var validators = $target.data('Validators');
                if (validators) {
                    for (var i = 0; i < Object.keys(validators).length; i++) {
                        var validator = validators[Object.keys(validators)[i]];
                        $target.removeClass(defaults.invalidCls).trigger('ValidationCleared', validator);
                    }
                }
            });

            return $toClear; // Enable chaining
        },
        find: function(key) {
            var validators = [];

            this.each(function() {
                var $target = $(this); // 'this' is now a single element
                var _validators = $target.data('Validators');
                if (_validators && _validators[key]) {
        ...