From 6218258bfadd6ff7724e276cbf55569a3aaa6c21 Mon Sep 17 00:00:00 2001 From: Jay El-Kaake Date: Sat, 31 Oct 2015 13:46:10 -0400 Subject: [PATCH] Updated with some fixed functionality and better out-of-box performance. --- js/valid8.js | 351 ++++++++++++++++++++++++++++------------------- js/valid8.min.js | 2 +- 2 files changed, 208 insertions(+), 145 deletions(-) diff --git a/js/valid8.js b/js/valid8.js index 3b57b14..dd1651e 100644 --- a/js/valid8.js +++ b/js/valid8.js @@ -4,148 +4,181 @@ * @requires jQuery (pretty much any version will work). Works best with Bootstrap. * */ - -var Valid8 = { - validators: [], - add: function(className, msg, validationFunc) { - Valid8.validators.push([className, msg, validationFunc]); - }, - addAll: function(arr) { - for (var i = 0; i < arr.length; i++) { - Valid8.validators.push(arr[i]); - } - }, - getValidationMsg: function(val, className) { - for (var i = Valid8.validators.length - 1; i >= 0; i--) { - var validator = Valid8.validators[i]; - if (validator[0] != className) { - continue; +(function($) { + var Valid8 = { + validators: [], + /** + * Add a validation type + * @param {[type]} className [description] + * @param {[type]} msg [description] + * @param {[type]} validationFunc [description] + */ + add: function(className, msg, validationFunc) { + Valid8.validators.push([className, msg, validationFunc]); + }, + /** + * Add an array of validation types + * @param {[type]} arr [description] + */ + addAll: function(arr) { + for (var i = 0; i < arr.length; i++) { + Valid8.validators.push(arr[i]); } - if (!validator[2](val)) { - return validator[1]; + }, + /** + * Get the validation message for a given validation class name + * given the value of the input. + * @param {[type]} val [description] + * @param {[type]} className [description] + * @return {[type]} [description] + */ + getValidationMsg: function(val, className) { + for (var i = Valid8.validators.length - 1; i >= 0; i--) { + var validator = Valid8.validators[i]; + if (validator[0] != className) { + continue; + } + if (!validator[2](val)) { + return validator[1]; + } + return null; } return null; - } - return null; - }, - isValid: function(val, className) { - for (var i = Valid8.validators.length - 1; i >= 0; i--) { - var validator = Valid8.validators[i]; - if (validator[0] != className) { - continue; - } - if (!validator[2](val)) { - return false; + }, + /** + * Is a field valid for the given validation class name? + * @param {[type]} val [description] + * @param {[type]} className [description] + * @return {Boolean} [description] + */ + isValid: function(val, className) { + for (var i = Valid8.validators.length - 1; i >= 0; i--) { + var validator = Valid8.validators[i]; + if (validator[0] != className) { + continue; + } + if (!validator[2](val)) { + return false; + } + return true; } return true; - } - return true; - }, - isEmpty: function(v) { - return ((v === null) || (v.length === 0)); // || /^\s+$/.test(v)); - } -}; + }, + /** + * Is a value empty? + * @return {Boolean} + */ + isEmpty: function(v) { + return ((v === null) || (v.length === 0)); // || /^\s+$/.test(v)); + } + }; + + /** + * Let's define a bunch of validations + */ + Valid8.addAll([ + ['required', 'This is a required field.', + function(v) { + return !Valid8.isEmpty(v); + } + ], + ['validate-number', 'Please enter a valid number in this field.', + function(v) { + return Valid8.isEmpty(v) || (!isNaN(v) && !/^\s+$/.test(v)); + } + ], + ['validate-digits', 'Please use numbers only in this field. please avoid spaces or other characters such as dots or commas.', + function(v) { + return Valid8.isEmpty(v) || !/[^\d]/.test(v); + } + ], + ['validate-alpha', 'Please use letters only (a-z) in this field.', + function(v) { + return Valid8.isEmpty(v) || /^[a-zA-Z]+$/.test(v); + } + ], + ['validate-alphanum', 'Please use only letters (a-z) or numbers (0-9) only in this field. No spaces or other characters are allowed.', + function(v) { + return Valid8.isEmpty(v) || !/\W/.test(v); + } + ], + ['validate-creditcard', 'Please enter a valid credit card number.', + function(v) { + var ccreg = /^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/; + return Valid8.isEmpty(v) || ccreg.test(v.replace(/ /g,'')); + } + ], + ['validate-date', 'Please enter a valid date.', + function(v) { + //var test = new Date(v); + //return Valid8.isEmpty(v) || !isNaN(test); + if (Valid8.isEmpty(v)) return true; + var regex = /^(\d{2})\/(\d{2})\/(\d{4})$/; + if (!regex.test(v)) return false; + var d = new Date(v); + return (parseInt(RegExp.$2, 10) == (1 + d.getMonth())) && + (parseInt(RegExp.$1, 10) == d.getDate()) && + (parseInt(RegExp.$3, 10) == d.getFullYear()); + } + ], + ['validate-email', 'Please enter a valid email address. For example john@example.com.', + function(v) { + return Valid8.isEmpty(v) || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(v); + } + ], + ['validate-url', 'Please enter a valid URL.', + function(v) { + return Valid8.isEmpty(v) || /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test(v); + } + ], + ['validate-date-au', 'Please use this date format: dd/mm/yyyy. For example 17-03-2006 for the 17th of March, 2006.', + function(v) { // Bootstrap stores dates as 2015-02-20 yyyy-mm-dd + if (Valid8.isEmpty(v)) return true; + var regex = /^(\d{4})-(\d{2})-(\d{2})$/; + if (!regex.test(v)) return false; + var d = new Date(v.replace(regex, '$2/$3/$1')); + return (parseInt(RegExp.$2, 10) == (1 + d.getMonth())) && + (parseInt(RegExp.$3, 10) == d.getDate()) && + (parseInt(RegExp.$1, 10) == d.getFullYear()); + } + ], + ['validate-currency-dollar', 'Please enter a valid $ amount. For example $100.00 .', + function(v) { + // [$]1[##][,###]+[.##] + // [$]1###+[.##] + // [$]0.## + // [$].## + return Valid8.isEmpty(v) || /^\$?\-?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/.test(v); + } + ], + ['validate-selection', 'Please make a selection', + function(v, elm) { + return elm.options ? elm.selectedIndex > 0 : !Valid8.isEmpty(v); + } + ], + ['validate-one-required', 'Please select one of the above options.', + function(v, elm) { + var p = elm.parentNode; + var options = p.getElementsByTagName('INPUT'); + return $A(options).any(function(elm) { + return $F(elm); + }); + } + ] + ]); -Valid8.addAll([ - ['required', 'This is a required field.', - function(v) { - return !Valid8.isEmpty(v); - } - ], - ['validate-number', 'Please enter a valid number in this field.', - function(v) { - return Valid8.isEmpty(v) || (!isNaN(v) && !/^\s+$/.test(v)); - } - ], - ['validate-digits', 'Please use numbers only in this field. please avoid spaces or other characters such as dots or commas.', - function(v) { - return Valid8.isEmpty(v) || !/[^\d]/.test(v); - } - ], - ['validate-alpha', 'Please use letters only (a-z) in this field.', - function(v) { - return Valid8.isEmpty(v) || /^[a-zA-Z]+$/.test(v); - } - ], - ['validate-alphanum', 'Please use only letters (a-z) or numbers (0-9) only in this field. No spaces or other characters are allowed.', - function(v) { - return Valid8.isEmpty(v) || !/\W/.test(v); - } - ], - ['validate-creditcard', 'Please enter a valid credit card number.', - function(v) { - var ccreg = /^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/; - return Valid8.isEmpty(v) || ccreg.test(v.replace(/ /g,'')); - } - ], - ['validate-date', 'Please enter a valid date.', - function(v) { - //var test = new Date(v); - //return Valid8.isEmpty(v) || !isNaN(test); - if (Valid8.isEmpty(v)) return true; - var regex = /^(\d{2})\/(\d{2})\/(\d{4})$/; - if (!regex.test(v)) return false; - var d = new Date(v); - return (parseInt(RegExp.$2, 10) == (1 + d.getMonth())) && - (parseInt(RegExp.$1, 10) == d.getDate()) && - (parseInt(RegExp.$3, 10) == d.getFullYear()); - } - ], - ['validate-email', 'Please enter a valid email address. For example john@example.com.', - function(v) { - return Valid8.isEmpty(v) || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(v); - } - ], - ['validate-url', 'Please enter a valid URL.', - function(v) { - return Valid8.isEmpty(v) || /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test(v); - } - ], - ['validate-date-au', 'Please use this date format: dd/mm/yyyy. For example 17-03-2006 for the 17th of March, 2006.', - function(v) { // Bootstrap stores dates as 2015-02-20 yyyy-mm-dd - if (Valid8.isEmpty(v)) return true; - var regex = /^(\d{4})-(\d{2})-(\d{2})$/; - if (!regex.test(v)) return false; - var d = new Date(v.replace(regex, '$2/$3/$1')); - return (parseInt(RegExp.$2, 10) == (1 + d.getMonth())) && - (parseInt(RegExp.$3, 10) == d.getDate()) && - (parseInt(RegExp.$1, 10) == d.getFullYear()); - } - ], - ['validate-currency-dollar', 'Please enter a valid $ amount. For example $100.00 .', - function(v) { - // [$]1[##][,###]+[.##] - // [$]1###+[.##] - // [$]0.## - // [$].## - return Valid8.isEmpty(v) || /^\$?\-?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/.test(v); - } - ], - ['validate-selection', 'Please make a selection', - function(v, elm) { - return elm.options ? elm.selectedIndex > 0 : !Valid8.isEmpty(v); - } - ], - ['validate-one-required', 'Please select one of the above options.', - function(v, elm) { - var p = elm.parentNode; - var options = p.getElementsByTagName('INPUT'); - return $A(options).any(function(elm) { - return $F(elm); - }); - } - ] -]); + /** + * Alright, here's the setup of our page + * so we don't have to do anything. + */ + $(document).ready(function() { + $("form").each(function() { + var $form = $(this); -$(document).ready(function() { - $("form").each(function() { - var $form = $(this); - // Add input checkers. - $form.find(':input').each(function() { - var $input = $(this); - $input.change(function(e) { + // Check a single field for validity + var checkField = function($input) { var isValid = true; var validationMsg; @@ -172,19 +205,49 @@ $(document).ready(function() { } else { $input.removeClass("valid-input").addClass('invalid-input').parent().addClass('has-error'); } - }); - }); + }; - // Add form complete check - $form.change(function(e) { - if($form.find('.has-error').length > 0) { - $form.find('[type=submit]').addClass('disabled'); - } else { - $form.find('[type=submit]').removeClass('disabled'); + // Check all Fields + var checkFields = function() { + $form.find(':input').each(function() { + checkField($(this)); + }); } + + // Add input checkers. + $form.find(':input').each(function() { + var $input = $(this); + $input.change(function(e) { + checkField($input); + }); + }); + + // Add form complete check + $form.change(function(e) { + if($form.find('.has-error').length > 0) { + $form.find('[type=submit]').addClass('disabled'); + } else { + $form.find('[type=submit]').removeClass('disabled'); + } + }); + + // Check all fields upon submit + $form.on('submit', function() { + var $submit = $form.find('[type=submit]'); + checkFields(); + if($form.find('.has-error').length > 0) { + $submit.addClass('disabled'); + return false; + } else { + $submit.removeClass('disabled'); + return true; + } + }); + }); + // We need a default validation CSS style so we don't require everyone + // to define styles or include a CSS file if they don't want to. + $('body').append(""); }); - - $('body').append(""); -}); +})(jQuery); diff --git a/js/valid8.min.js b/js/valid8.min.js index 6c318f7..b8adc17 100644 --- a/js/valid8.min.js +++ b/js/valid8.min.js @@ -1 +1 @@ -var Valid8={validators:[],add:function(e,a,t){Valid8.validators.push([e,a,t])},addAll:function(e){for(var a=0;a=0;t--){var i=Valid8.validators[t];if(i[0]==a)return i[2](e)?null:i[1]}return null},isValid:function(e,a){for(var t=Valid8.validators.length-1;t>=0;t--){var i=Valid8.validators[t];if(i[0]==a)return i[2](e)?!0:!1}return!0},isEmpty:function(e){return null===e||0===e.length}};Valid8.addAll([["required","This is a required field.",function(e){return!Valid8.isEmpty(e)}],["validate-number","Please enter a valid number in this field.",function(e){return Valid8.isEmpty(e)||!isNaN(e)&&!/^\s+$/.test(e)}],["validate-digits","Please use numbers only in this field. please avoid spaces or other characters such as dots or commas.",function(e){return Valid8.isEmpty(e)||!/[^\d]/.test(e)}],["validate-alpha","Please use letters only (a-z) in this field.",function(e){return Valid8.isEmpty(e)||/^[a-zA-Z]+$/.test(e)}],["validate-alphanum","Please use only letters (a-z) or numbers (0-9) only in this field. No spaces or other characters are allowed.",function(e){return Valid8.isEmpty(e)||!/\W/.test(e)}],["validate-creditcard","Please enter a valid credit card number.",function(e){var a=/^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/;return Valid8.isEmpty(e)||a.test(e.replace(/ /g,""))}],["validate-date","Please enter a valid date.",function(e){if(Valid8.isEmpty(e))return!0;var a=/^(\d{2})\/(\d{2})\/(\d{4})$/;if(!a.test(e))return!1;var t=new Date(e);return parseInt(RegExp.$2,10)==1+t.getMonth()&&parseInt(RegExp.$1,10)==t.getDate()&&parseInt(RegExp.$3,10)==t.getFullYear()}],["validate-email","Please enter a valid email address. For example john@example.com.",function(e){return Valid8.isEmpty(e)||/\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(e)}],["validate-url","Please enter a valid URL.",function(e){return Valid8.isEmpty(e)||/^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test(e)}],["validate-date-au","Please use this date format: dd/mm/yyyy. For example 17-03-2006 for the 17th of March, 2006.",function(e){if(Valid8.isEmpty(e))return!0;var a=/^(\d{4})-(\d{2})-(\d{2})$/;if(!a.test(e))return!1;var t=new Date(e.replace(a,"$2/$3/$1"));return parseInt(RegExp.$2,10)==1+t.getMonth()&&parseInt(RegExp.$3,10)==t.getDate()&&parseInt(RegExp.$1,10)==t.getFullYear()}],["validate-currency-dollar","Please enter a valid $ amount. For example $100.00 .",function(e){return Valid8.isEmpty(e)||/^\$?\-?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/.test(e)}],["validate-selection","Please make a selection",function(e,a){return a.options?a.selectedIndex>0:!Valid8.isEmpty(e)}],["validate-one-required","Please select one of the above options.",function(e,a){var t=a.parentNode,i=t.getElementsByTagName("INPUT");return $A(i).any(function(e){return $F(e)})}]]),$(document).ready(function(){$("form").each(function(){var e=$(this);e.find(":input").each(function(){var e=$(this);e.change(function(){var a,t=!0;0===e.next(".validation-msg").length&&e.after("");var i=e.next(".validation-msg");$(e.attr("class").split(" ")).each(function(i,n){a=a||Valid8.getValidationMsg(e.val(),n),a&&(t=!1)}),t?i.hide():i.html(a).show(),t?e.addClass("valid-input").removeClass("invalid-input").parent().removeClass("has-error"):e.removeClass("valid-input").addClass("invalid-input").parent().addClass("has-error")})}),e.change(function(){e.find(".has-error").length>0?e.find("[type=submit]").addClass("disabled"):e.find("[type=submit]").removeClass("disabled")})}),$("body").append("")}); \ No newline at end of file +!function(e){var t={validators:[],add:function(e,a,n){t.validators.push([e,a,n])},addAll:function(e){for(var a=0;a=0;n--){var i=t.validators[n];if(i[0]==a)return i[2](e)?null:i[1]}return null},isValid:function(e,a){for(var n=t.validators.length-1;n>=0;n--){var i=t.validators[n];if(i[0]==a)return i[2](e)?!0:!1}return!0},isEmpty:function(e){return null===e||0===e.length}};t.addAll([["required","This is a required field.",function(e){return!t.isEmpty(e)}],["validate-number","Please enter a valid number in this field.",function(e){return t.isEmpty(e)||!isNaN(e)&&!/^\s+$/.test(e)}],["validate-digits","Please use numbers only in this field. please avoid spaces or other characters such as dots or commas.",function(e){return t.isEmpty(e)||!/[^\d]/.test(e)}],["validate-alpha","Please use letters only (a-z) in this field.",function(e){return t.isEmpty(e)||/^[a-zA-Z]+$/.test(e)}],["validate-alphanum","Please use only letters (a-z) or numbers (0-9) only in this field. No spaces or other characters are allowed.",function(e){return t.isEmpty(e)||!/\W/.test(e)}],["validate-creditcard","Please enter a valid credit card number.",function(e){var a=/^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/;return t.isEmpty(e)||a.test(e.replace(/ /g,""))}],["validate-date","Please enter a valid date.",function(e){if(t.isEmpty(e))return!0;var a=/^(\d{2})\/(\d{2})\/(\d{4})$/;if(!a.test(e))return!1;var n=new Date(e);return parseInt(RegExp.$2,10)==1+n.getMonth()&&parseInt(RegExp.$1,10)==n.getDate()&&parseInt(RegExp.$3,10)==n.getFullYear()}],["validate-email","Please enter a valid email address. For example john@example.com.",function(e){return t.isEmpty(e)||/\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(e)}],["validate-url","Please enter a valid URL.",function(e){return t.isEmpty(e)||/^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test(e)}],["validate-date-au","Please use this date format: dd/mm/yyyy. For example 17-03-2006 for the 17th of March, 2006.",function(e){if(t.isEmpty(e))return!0;var a=/^(\d{4})-(\d{2})-(\d{2})$/;if(!a.test(e))return!1;var n=new Date(e.replace(a,"$2/$3/$1"));return parseInt(RegExp.$2,10)==1+n.getMonth()&&parseInt(RegExp.$3,10)==n.getDate()&&parseInt(RegExp.$1,10)==n.getFullYear()}],["validate-currency-dollar","Please enter a valid $ amount. For example $100.00 .",function(e){return t.isEmpty(e)||/^\$?\-?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/.test(e)}],["validate-selection","Please make a selection",function(e,a){return a.options?a.selectedIndex>0:!t.isEmpty(e)}],["validate-one-required","Please select one of the above options.",function(e,t){var a=t.parentNode,n=a.getElementsByTagName("INPUT");return $A(n).any(function(e){return $F(e)})}]]),e(document).ready(function(){e("form").each(function(){var a=e(this),n=function(a){var n,i=!0;0===a.next(".validation-msg").length&&a.after("");var r=a.next(".validation-msg");e(a.attr("class").split(" ")).each(function(e,r){n=n||t.getValidationMsg(a.val(),r),n&&(i=!1)}),i?r.hide():r.html(n).show(),i?a.addClass("valid-input").removeClass("invalid-input").parent().removeClass("has-error"):a.removeClass("valid-input").addClass("invalid-input").parent().addClass("has-error")},i=function(){a.find(":input").each(function(){n(e(this))})};a.find(":input").each(function(){var t=e(this);t.change(function(){n(t)})}),a.change(function(){a.find(".has-error").length>0?a.find("[type=submit]").addClass("disabled"):a.find("[type=submit]").removeClass("disabled")}),a.on("submit",function(){var e=a.find("[type=submit]");return i(),a.find(".has-error").length>0?(e.addClass("disabled"),!1):(e.removeClass("disabled"),!0)})}),e("body").append("")})}(jQuery); \ No newline at end of file