Uunknownn
4/27/2017 - 3:27 AM

jQuery Form Validator Plugin ©

jQuery Form Validator Plugin ©

$.fn.extend({validate:function(a){"use strict";for(var b=[],c=[],d=[],e=this[0].elements.length-1;e--;)d.unshift(this[0].elements[e]);var f={required:"This field is required.",nospace:"No white-spaces allowed!",integer:"This field must be an integer.",alpha:"This field must contain alphabetic characters only.",alphanum:"This field must contain alpha-numeric characters only.",special:"This field must contain alpha-numeric characters only. Some special characters allowed (_-!@#$%&*+).",real:"This field must contain a real number.",pos:"The value must be positive.",email:"This field must contain a valid email address.",match:"This field must match the required one.",number:"This field must contain a number within the required range.",range:function(a,b,c){return"This field must contain a number between "+a+" and "+b+". "+c+" given."},len:function(a,b,c){return"This field must contain between "+a+" and "+b+" characters. "+c+" given."},exact_len:function(a,b){return"This field must contain exactly "+a+" characters. "+b+" given."}};String.prototype.remWS=function(){return this.replace(/ /g,"").trim()},String.prototype.oneWS=function(){return this.replace(/[ ]+/g," ").trim()},String.prototype.remSN=function(){return this.replace(/[\+]/g,"")};var g={required:function(b){return""!==b.value.trim()||($(b).parent().addClass("has-error"),$(b).val(b.value.remWS()),b.focus(),$(b).next().text(f.required),a&&a({success:0,msg:f.required}),!1)},nospace:function(b){return console.log("content"),!/[ \n]+/i.test(b.value)||($(b).focus(),$(b).parent().addClass("has-error"),$(b).next().text(f.nospace),a&&a({success:0,msg:f.nospace}),!1)},int:function(b){return/[^\-+0-9]/i.test(b.value)?($(b).focus(),$(b).parent().addClass("has-error"),$(b).next().text(f.integer),a&&a({success:0,msg:f.integer}),!1):(b.value=b.value.remSN(),!0)},alpha:function(b){return!/[^\n a-zãõñâêîôûáéíóúàèìòùäëïöüç]/i.test(b.value)||($(b).focus(),$(b).parent().addClass("has-error"),$(b).next().text(f.alpha),a&&a({success:0,msg:f.alpha}),!1)},alphanum:function(b){return!/[^\n a-z0-9ãõñâêîôûáéíóúàèìòùäëïöüç]/i.test(b.value)||($(b).focus(),$(b).parent().addClass("has-error"),$(b).next().text(f.alphanum),a&&a({success:0,msg:f.alphanum}),!1)},special:function(b){return!/[^\n 0-9a-zãõñâêîôûáéíóúàèìòùäëïöüç_\-!@#$%&*+]+/i.test(b.value)||($(b).focus(),$(b).parent().addClass("has-error"),$(b).next().text(f.special),a&&a({success:0,msg:f.special}),!1)},real:function(b){return!!/^([\-+0-9]+)([.0-9])([0-9]+)$/.test(b.value)||($(b).focus(),$(b).parent().addClass("has-error"),$(b).next().text(f.real),a&&a({success:0,msg:f.real}),!1)},pos:function(b){return!!/^([+0-9.]+)$/i.test(b.value)||($(b).focus(),$(b).parent().addClass("has-error"),$(b).next().text(f.pos),a&&a({success:0,msg:f.pos}),!1)},email:function(b){return!!/^([\w\-\.]+)@([\a-z0-9\.-]+)([a-z0-9]{2,3})$/i.test(b.value)||($(b).focus(),$(b).parent().addClass("has-error"),$(b).next().text(f.email),a&&a({success:0,msg:f.email}),!1)},match:function(b,c){var d=document.getElementsByName(c)[0];return b.value===d.value||($(b).focus(),$(b).parent().addClass("has-error"),$(d).parent().addClass("has-error"),$(b).next().text(f.match),a&&a({success:0,msg:f.match}),!1)},len:function(b,c){var d=b.value.oneWS().length;return void 0===c[1]&&d!=c[0]?($(b).focus(),b.value=b.value.oneWS(),$(b).parent().addClass("has-error"),$(b).next().text(f.exact_len(c,d)),a&&a({success:0,msg:f.exact_len(c,d)}),!1):d<c[0]||d>c[1]?($(b).focus(),b.value=b.value.oneWS(),$(b).parent().addClass("has-error"),$(b).next().text(f.len(c[0],c[1],d)),a&&a({success:0,msg:f.len(c[0],c[1],d)}),!1):(b.value=b.value.oneWS(),!0)},range:function(b,c){var d=parseFloat(b.value);return isNaN(d)?($(b).focus(),$(b).parent().addClass("has-error"),$(b).next().text(f.number),a&&a({success:0,msg:f.number}),!1):!(d<parseFloat(c[0])||d>parseFloat(c[1]))||($(b).focus(),$(b).parent().addClass("has-error"),$(b).next().text(f.range(c[0],c[1],d)),a&&a({success:0,msg:f.range(c[0],c[1],d)}),!1)}};for(var h in d)$(d[h]).parent().find(".help-block").length?$(d[h]).parent().find(".help-block").text(""):$(d[h]).after('<div class="help-block"></div>'),$(d[h]).parent().hasClass("has-error")&&$(d[h]).parent().removeClass("has-error");for(var h in d)if(void 0!=$(d[h]).data("validate")){b=$(d[h]).data("validate").split("|");for(var i in b)if(/len/.test(b[i])){if(c=b[i].match(/[0-9]+/g),!g.len(d[h],c))return!1}else if(/match/.test(b[i])){if(c=b[i].match(/(?:\[)([a-z0-9\-_]+)/i)[1].toString(),!g.match(d[h],c))return!1}else if(/range/.test(b[i])){if(c=b[i].match(/[0-9]+/g),!g.range(d[h],c))return!1}else if(!g[b[i]](d[h]))return!1}a&&a({success:1})}});
$.fn.extend({
    validate: function(callback) {
        'use strict';

        var rules = [];
        var params = [];
        var field_list = [];

        var size = this[0].elements.length - 1;

        while (size--) {
            field_list.unshift(this[0].elements[size]);
        }

        var responses = {
            required: 'This field is required.',
            nospace: 'No white-spaces allowed!',
            integer: 'This field must be an integer.',
            alpha: 'This field must contain alphabetic characters only.',
            alphanum: 'This field must contain alpha-numeric characters only.',
            special: 'This field must contain alpha-numeric characters only. Some special characters allowed (_-!@#$%&*+).',
            real: 'This field must contain a real number.',
            pos: 'The value must be positive.',
            email: 'This field must contain a valid email address.',
            match: "This field must match the required one.",
            number: 'This field must contain a number within the required range.',
            range: function(min, max, given) {
                return 'This field must contain a number between ' + min + ' and ' + max + '. ' + given + ' given.';
            },
            len: function(min, max, given) {
                return 'This field must contain between ' + min + ' and ' + max + ' characters. ' + given + ' given.';
            },
            exact_len: function(exact, given) {
                return 'This field must contain exactly ' + exact + ' characters. ' + given + ' given.';
            }
        }

        // REMOVE WHITE SPACES
        String.prototype.remWS = function() {
            return this.replace(/ /g, '').trim();
        }

        // SINGLE WHITE SPACE
        String.prototype.oneWS = function() {
            return this.replace(/[ ]+/g, ' ').trim();
        }

        // REMOVE SIGNALS
        String.prototype.remSN = function() {
            return this.replace(/[\+]/g, '');
        }



        //----------------------------------
        // SET UP RULES
        //----------------------------------
        var check = {

            //----------------------------------
            // REQUIRED FIELD (required)
            //----------------------------------
            required: function(field) {
                if (field.value.trim() === '') {
                    $(field).parent().addClass('has-error');
                    $(field).val(field.value.remWS());
                    field.focus();
                    $(field).next().text(responses.required);
                    if (callback) callback({
                        success: 0,
                        msg: responses.required
                    });
                    return false;
                }

                return true;
            },


            //----------------------------------
            // NO WHITE SPACES ALLOWED (nospace)
            //----------------------------------
            nospace: function(field) {

                console.log('content');

                if (/[ \n]+/i.test(field.value)) {
                    $(field).focus();
                    $(field).parent().addClass('has-error');
                    $(field).next().text(responses.nospace);
                    if (callback) callback({
                        success: 0,
                        msg: responses.nospace
                    });
                    return false;
                }

                return true;
            },


            //----------------------------------
            // INTEGER VALUE (int)
            //----------------------------------
            int: function(field) {

                if (/[^\-+0-9]/i.test(field.value)) {
                    $(field).focus();
                    $(field).parent().addClass('has-error');
                    $(field).next().text(responses.integer);
                    if (callback) callback({
                        success: 0,
                        msg: responses.integer
                    });
                    return false;
                }

                field.value = field.value.remSN();
                return true;
            },


            //----------------------------------
            // ALPHA-CHARACTERS ONLY (alpha)
            //----------------------------------
            alpha: function(field) {

                if (/[^\n a-zãõñâêîôûáéíóúàèìòùäëïöüç]/i.test(field.value)) {
                    $(field).focus();
                    $(field).parent().addClass('has-error');
                    $(field).next().text(responses.alpha);
                    if (callback) callback({
                        success: 0,
                        msg: responses.alpha
                    });
                    return false;
                }

                return true;
            },


            //----------------------------------
            // ALPHA-NUMERIC ONLY (alphanum)
            //----------------------------------
            alphanum: function(field) {

                if (/[^\n a-z0-9ãõñâêîôûáéíóúàèìòùäëïöüç]/i.test(field.value)) {
                    $(field).focus();
                    $(field).parent().addClass('has-error');
                    $(field).next().text(responses.alphanum);
                    if (callback) callback({
                        success: 0,
                        msg: responses.alphanum
                    });
                    return false;
                }

                return true;
            },


            //----------------------------------
            // SPECIAL & ALPHA-NUMERIC (special)
            //----------------------------------
            special: function(field) {

                if (/[^\n 0-9a-zãõñâêîôûáéíóúàèìòùäëïöüç_\-!@#$%&*+]+/i.test(field.value)) {
                    $(field).focus();
                    $(field).parent().addClass('has-error');
                    $(field).next().text(responses.special);
                    if (callback) callback({
                        success: 0,
                        msg: responses.special
                    });
                    return false;
                }

                return true;
            },


            //----------------------------------
            // REAL (real)
            //----------------------------------
            real: function(field) {

                if (!/^([\-+0-9]+)([.0-9])([0-9]+)$/.test(field.value)) {
                    $(field).focus();
                    $(field).parent().addClass('has-error');
                    $(field).next().text(responses.real);
                    if (callback) callback({
                        success: 0,
                        msg: responses.real
                    });
                    return false;
                }

                return true;
            },


            //----------------------------------
            // POSITIVE (pos)
            //----------------------------------
            pos: function(field) {

                if (!/^([+0-9.]+)$/i.test(field.value)) {
                    $(field).focus();
                    $(field).parent().addClass('has-error');
                    $(field).next().text(responses.pos);
                    if (callback) callback({
                        success: 0,
                        msg: responses.pos
                    });
                    return false;
                }

                return true;
            },


            //----------------------------------
            // EMAIL (email)
            //----------------------------------
            email: function(field) {

                if (!/^([\w\-\.]+)@([\a-z0-9\.-]+)([a-z0-9]{2,3})$/i.test(field.value)) {
                    $(field).focus();
                    $(field).parent().addClass('has-error');
                    $(field).next().text(responses.email);
                    if (callback) callback({
                        success: 0,
                        msg: responses.email
                    });
                    return false;
                }

                return true;
            },


            //----------------------------------
            // MATCH (match[name])
            //----------------------------------
            match: function(field, matchField) {

                var required = document.getElementsByName(matchField)[0];

                if (field.value !== required.value) {
                    $(field).focus();
                    $(field).parent().addClass('has-error');
                    $(required).parent().addClass('has-error');
                    $(field).next().text(responses.match);
                    if (callback) callback({
                        success: 0,
                        msg: responses.match
                    });
                    return false;
                }

                return true;
            },


            //----------------------------------
            // LENGTH (len[min, max] or len[exact])
            //----------------------------------
            len: function(field, range) {

                var given = field.value.oneWS().length;

                if (range[1] === undefined && given != range[0]) {

                    $(field).focus();
                    field.value = field.value.oneWS();
                    $(field).parent().addClass('has-error');
                    $(field).next().text(responses.exact_len(range, given));
                    if (callback) callback({
                        success: 0,
                        msg: responses.exact_len(range, given)
                    });
                    return false;
                } else if (given < range[0] || given > range[1]) {
                    $(field).focus();
                    field.value = field.value.oneWS();
                    $(field).parent().addClass('has-error');
                    $(field).next().text(responses.len(range[0], range[1], given));
                    if (callback) callback({
                        success: 0,
                        msg: responses.len(range[0], range[1], given)
                    });
                    return false;
                }

                field.value = field.value.oneWS();
                return true;
            },


            //----------------------------------
            // RANGE (range[min,max])
            //----------------------------------
            range: function(field, range) {

                var given = parseFloat(field.value);

                if (isNaN(given)) {
                    $(field).focus();
                    $(field).parent().addClass('has-error');
                    $(field).next().text(responses.number);
                    if (callback) callback({
                        success: 0,
                        msg: responses.number
                    });
                    return false;
                } else if (given < parseFloat(range[0]) || given > parseFloat(range[1])) {
                    $(field).focus();
                    $(field).parent().addClass('has-error');
                    $(field).next().text(responses.range(range[0], range[1], given));
                    if (callback) callback({
                        success: 0,
                        msg: responses.range(range[0], range[1], given)
                    });
                    return false;
                }

                return true;
            }


        }


        //----------------------------------
        // PERFORM THE VALIDATOR
        //----------------------------------


        for (var i in field_list) {
            if ($(field_list[i]).parent().find('.help-block').length) {
                $(field_list[i]).parent().find('.help-block').text('');
            } else {
                $(field_list[i]).after('<div class="help-block"></div>');
            }

            if ($(field_list[i]).parent().hasClass('has-error')) {
                $(field_list[i]).parent().removeClass('has-error');
            }
        }


        for (var i in field_list) {

            if ($(field_list[i]).data('validate') != undefined) {
                rules = $(field_list[i]).data('validate').split('|');

                for (var x in rules) {

                    if (/len/.test(rules[x])) {
                        params = rules[x].match(/[0-9]+/g);

                        if (!check.len(field_list[i], params)) {
                            return false;
                        }
                    } else if (/match/.test(rules[x])) {
                        params = rules[x].match(/(?:\[)([a-z0-9\-_]+)/i)[1].toString();

                        if (!check.match(field_list[i], params)) {
                            return false;
                        }
                    } else if (/range/.test(rules[x])) {
                        params = rules[x].match(/[0-9]+/g);

                        if (!check.range(field_list[i], params)) {
                            return false;
                        }
                    } else {
                        if (!check[rules[x]](field_list[i])) {
                            return false;
                        }
                    }

                }
            }

        }


        if (callback) {
            callback({
                success: 1
            });
        }
    }
});

jQuery Form Validator Plugin

Public CDN
Demo

Just link the script to your website, right after the jQuery

<script src="jquery.min.js"></script>
<script src="validator.min.js"></script>

Pass the submitted data through the validator

$('#loginForm').on('submit', function(e) {
  e.preventDefault();

  $(this).validate(function(data) {
    if (data.success) {
      // DO WHATEVER YOU WANT IF THERE IS NO ERROR
      alert("All data are valid!");
    } else {
      // RETURN THE ERROR MESSAGE IF THERE IS ONE
      alert(data.msg);
    }
  });

});

Prepare the fields to be verified

<input name="username" data-validate="required|len[6,12]|alphanum">

Valid Filters

filter namerule
required fieldrequired
set length (min and max or exact)len[min,max] or len[exactly]
alphabetic characters onlyalpha
alpha+numeric characters onlyalphanum
integer number onlyint
real number onlyreal
positive number onlypos
valid email addressemail
match selected fieldmatch[field_name]
all common + special characters allowed (!@#$%&*)special
number inside the given rangerange[min,max]
no spaces or linebreaks allowednospace