diff --git a/dist/uni-form-validation.jquery.js b/dist/uni-form-validation.jquery.js index dc2fc13..9475040 100644 --- a/dist/uni-form-validation.jquery.js +++ b/dist/uni-form-validation.jquery.js @@ -59,39 +59,6 @@ return text.replace('*', '').replace(':', ''); // Pretty formatting }; - // Set the results of form validation on the form element - $.uniform.validate = function ($input, isValid, errorMessage, errors, options) { - var $p, name; - options = options || $.uniform.defaultOptions; - $p = $input - .closest('div.' + options.holder_class) - .andSelf() - .toggleClass(options.error_class, !isValid) - .toggleClass(options.valid_class, isValid) - .find('p.form-hint'); - - name = $input.attr('name'); - - // Store this into the errors array, can be used by the custom callback - if (!isValid) { - errors[name] = errorMessage; - } - else if (name in errors) { - delete errors[name]; - } - - // If the validation failed we'll stash the p help text into the info-data - // and then put the error message in it's place. - if (!isValid && ! $p.data('info-text')) { - $p.data('info-text', $p.html()); - } - else if (isValid) { - errorMessage = $p.data('info-text'); - } - - if (errorMessage) { $p.html(errorMessage); } - }; - // Collection method will ppply the uniform behavior to elements $.fn.uniform = function (options) { @@ -132,6 +99,7 @@ if (options.ask_on_leave || $form.hasClass('askOnLeave')) { initial_values = $form.serialize(); $(window).bind("beforeunload", function () { + // We check options a second time so that we can disable this if ((initial_values !== $form.serialize()) && (options.ask_on_leave || $form.hasClass('askOnLeave')) ) { @@ -198,9 +166,7 @@ // QUnit needs to run this submit function, and still prevent the submit. // This isn't ideal, but it prevents us from having to trap events - if ($form.parents('#qunit-fixture').length) { - return_val = false; - } + if ($('#qunit-fixture').length) { return_val = false; } if (return_val === false) { $form.addClass('failedSubmit'); } @@ -209,9 +175,9 @@ // Set the form focus class and remove any classes other than the focus // class and then hide the default label text - $form.delegate(options.field_selector, 'focus', function () { + $form.find(options.field_selector).on('focus', function (e) { var $input = $(this); -window.console.log($input); +window.console.log(e); $form // Remove any other focus highlighting .find('.' + options.focused_class) .removeClass(options.focused_class); @@ -225,6 +191,7 @@ window.console.log($input); } $input.not('select').css('color', $input.data('default-color')); + }); // Validate a form field on the blur event @@ -233,7 +200,7 @@ window.console.log($input); // validators, and run them as we find them // // If the validators fail, we trigger either 'success' or 'error' events - $form.delegate(options.field_selector, 'blur', function () { + $form.find(options.field_selector).on('blur', function () { var $input = $(this), has_validation = false, validator, @@ -258,7 +225,7 @@ window.console.log($input); validation_result = $.uniform.validators[validator]($input, label, options); has_validation = true; if (typeof(validation_result) === 'string') { - $input.trigger('error', validation_result); + $input.trigger('uniform-error', validation_result); return; } } @@ -266,31 +233,30 @@ window.console.log($input); // If it had validation and we didn't return above, // then all validation passed - if (has_validation) { $input.trigger('success'); } + if (has_validation) { $input.trigger('uniform-success'); } // Return the color to the default $input.css('color', $input.data('default-color')); - return; - }); + }); // End Blur // Handle a validation error in the form element // This will set the field to have the error marker and update the // warning text - $form.delegate(options.field_selector, 'error', function (e, text) { - validate($(this), false, text, errors, options); + $form.on('uniform-error', options.field_selector, function (e, text) { + $.uniform.showValidation($(this), false, text, errors, options); }); // Handle a succesful validation in the form element // Remove any error messages and set the validation marker to be success - $form.delegate(options.field_selector, 'success', function () { - validate($(this), true, '', errors, options); + $form.on('uniform-success', options.field_selector, function () { + $.uniform.showValidation($(this), true, '', errors, options); }); - // Issue 9: HTML5 autofocus elements + // Issue 9: HTML5 autofocus element attribute // When the browser focuses, it happens before Uni-Form, and so we need // the manually run the focus event here to deal with style changes // and any handling of the default data - $('input[autofocus]:first').focus(); + $('input[autofocus]:first').trigger("focus"); return this; }); // end for each form @@ -336,6 +302,38 @@ window.console.log($input); return false; }; + // Set the results of form validation on the form element + $.uniform.showValidation = function ($input, isValid, errorMessage, errors, options) { + var $p, name; + options = options || $.uniform.defaultOptions; + $p = $input + .closest('div.' + options.holder_class) + .andSelf() + .toggleClass(options.error_class, !isValid) + .toggleClass(options.valid_class, isValid) + .find('p.form-hint'); + + name = $input.attr('name'); + + // Store this into the errors array, can be used by the custom callback + if (!isValid) { + errors[name] = errorMessage; + } + else if (name in errors) { + delete errors[name]; + } + + // If the validation failed we'll stash the p help text into the info-data + // and then put the error message in it's place. + if (!isValid && ! $p.data('info-text')) { + $p.data('info-text', $p.html()); + } + else if (isValid) { + errorMessage = $p.data('info-text'); + } + + if (errorMessage) { $p.html(errorMessage); } + }; // Simple replacement for i18n + sprintf // `$.uniform.i18n("string_key", sprintf style arguments)` diff --git a/dist/uni-form-validation.jquery.min.js b/dist/uni-form-validation.jquery.min.js index dac0d80..2b773c8 100644 --- a/dist/uni-form-validation.jquery.min.js +++ b/dist/uni-form-validation.jquery.min.js @@ -1,4 +1,4 @@ /*! Uni-Form - v1.5.0 - 2013-03-31 * http://sprawsm.com/uni-form/ * Copyright (c) 2013 Dragan Babic; Licensed MIT */ -(function(a){a.uniform=function(){},a.uniform.get_val=function(a,e,t){var l,n=t;for(e=e.split(" "),l=0;e.length>l;l+=1)if(e[l]===a&&"undefined"!==e[l+1]&&"val-"===e[l+1].substr(0,4))return n=parseInt(e[l+1].substr(4),10);return n},a.uniform.get_label_text=function(e,t){var l=e.closest("label").text();return t=t||a.uniform.defaultOptions,""===l&&(l=e.closest("div."+t.holder_class).find("label").text()),l.replace("*","").replace(":","")},a.uniform.validate=function(e,t,l,n,r){var s,i;r=r||a.uniform.defaultOptions,s=e.closest("div."+r.holder_class).andSelf().toggleClass(r.error_class,!t).toggleClass(r.valid_class,t).find("p.form-hint"),i=e.attr("name"),t?i in n&&delete n[i]:n[i]=l,t||s.data("info-text")?t&&(l=s.data("info-text")):s.data("info-text",s.html()),l&&s.html(l)},a.fn.uniform=function(e){return e=a.extend(a.uniform.defaultOptions,e),this.each(function(){var t,l,n,r,s,i;return t=a(this),l=[],n=a.proxy(a.uniform.get_label_text,this),r=a.proxy(a.uniform.get_val,this),s=a.proxy(a.uniform.validate,this),t.find(e.field_selector).each(function(){var t=a(this),l=t.val();t.data("default-color",t.css("color")),l!==t.data("default-value")&&l||(t.not("select").css("color",e.default_value_color),t.val(t.attr("data-default-value")))}),(e.ask_on_leave||t.hasClass("askOnLeave"))&&(i=t.serialize(),a(window).bind("beforeunload",function(){return i!==t.serialize()&&(e.ask_on_leave||t.hasClass("askOnLeave"))?a.isFunction(e.on_leave_callback)?e.on_leave_callback(t):window.confirm(a.uniform.i18n("on_leave")):void 0})),t.submit(function(){var l,n=!0;return t.removeClass("failedSubmit"),e.ask_on_leave=!1,t.removeClass("askOnLeave"),t.find(e.field_selector).each(function(){a(this).val()===a(this).data("default-value")&&a(this).val("")}),e.prevent_submit||t.hasClass("preventSubmit")?(t.find(e.field_selector).each(function(){a(this).blur()}),a.isFunction(e.submit_callback)&&(n=e.submit_callback(t)),(t.find("."+e.error_class).length||!n)&&(l=a.isFunction(e.prevent_submit_callback)?e.prevent_submit_callback(t,a.uniform.i18n("submit_msg"),[a.uniform.i18n("submit_help")]):a.uniform.showFormError(t,a.uniform.i18n("submit_msg"),[a.uniform.i18n("submit_help")]))):l=!0,t.parents("#qunit-fixture").length&&(l=!1),l===!1&&t.addClass("failedSubmit"),l}),t.delegate(e.field_selector,"focus",function(){var l=a(this);window.console.log(l),t.find("."+e.focused_class).removeClass(e.focused_class),l.closest("."+e.holder_class).addClass(e.focused_class),l.val()===l.data("default-value")&&l.val(""),l.not("select").css("color",l.data("default-color"))}),t.delegate(e.field_selector,"blur",function(){var l,r,s=a(this),i=!1,o=n(s,e);if(t.find("."+e.focused_class).removeClass(e.focused_class),(""===s.val()||s.val()===s.data("default-value"))&&!s.hasClass("required"))return s.not("select").css("color",e.default_value_color),s.val(s.data("default-value")),void 0;for(l in a.uniform.validators)if(s.hasClass(l)&&(r=a.uniform.validators[l](s,o,e),i=!0,"string"==typeof r))return s.trigger("error",r),void 0;i&&s.trigger("success"),s.css("color",s.data("default-color"))}),t.delegate(e.field_selector,"error",function(t,n){s(a(this),!1,n,l,e)}),t.delegate(e.field_selector,"success",function(){s(a(this),!0,"",l,e)}),a("input[autofocus]:first").focus(),this})},a.uniform.showFormError=function(e,t,l){var n,r;if(a("#errorMsg").length&&a("#errorMsg").remove(),r=a("
").attr("id","errorMsg").html("

"+t+"

"),l.length){r.append(a("
    "));for(n in l)l.hasOwnProperty(n)&&a("ol",r).append(a("
  1. ").text(l[n]))}return e.prepend(r),a("html, body").animate({scrollTop:e.offset().top},500),a("#errorMsg").slideDown(),!1},a.uniform.showFormSuccess=function(e,t){return a("#okMsg").remove(),e.prepend(a("
    ").attr("id","okMsg").html("

    "+t+"

    ")),a("html, body").animate({scrollTop:e.offset().top},500),a("#okMsg").slideDown(),!1},a.uniform.i18n=function(e){var t,l,n=a.uniform.language[e],r=n.split("%"),s=r[0],i=/^([ds])(.*)$/;for(l=1;r.length>l;l+=1)t=i.exec(r[l]),t&&null!==arguments[l]&&("d"===t[1]?s+=parseInt(arguments[l],10):"s"===t[1]&&(s+=arguments[l]),s+=t[2]);return s},a.uniform.language={required:"%s is required",req_radio:"Please make a selection",req_checkbox:"You must select this checkbox to continue",minlength:"%s should be at least %d characters long",min:"%s should be greater than or equal to %d",maxlength:"%s should not be longer than %d characters",max:"%s should be less than or equal to %d",same_as:"%s is expected to be same as %s",email:"%s is not a valid email address",url:"%s is not a valid URL",number:"%s needs to be a number",integer:"%s needs to be a whole number",alpha:"%s should contain only letters (without special characters or numbers)",alphanum:"%s should contain only numbers and letters (without special characters)",phrase:"%s should contain only alphabetic characters, numbers, spaces, and the following: . , - _ () * # :",phone:"%s should be a phone number",date:"%s should be a date (mm/dd/yyyy)",callback:"Failed to validate %s field. Validator function (%s) is not defined!",on_leave:"Are you sure you want to leave this page without saving this form?",submit_msg:"Sorry, this form needs corrections.",submit_help:"Please see the items marked below.",submit_success:"Thank you, this form has been sent."},a.uniform.defaultOptions={submit_callback:!1,prevent_submit:!1,prevent_submit_callback:!1,ask_on_leave:!1,on_leave_callback:!1,valid_class:"valid",error_class:"error",focused_class:"focused",holder_class:"ctrl-holder",hint_class:"form-hint",field_selector:"input, textarea, select",default_value_color:"#afafaf"}})(jQuery),function(a){a.uniform=a.uniform||{},a.uniform.validators={},a.uniform.validators.required=function(e,t){var l;return e.is(":radio")?(l=e.attr("name"),a("input[name="+l+"]:checked").length?!0:a.uniform.i18n("req_radio",t)):e.is(":checkbox")?(l=e.attr("name"),e.is(":checked")?!0:a.uniform.i18n("req_checkbox",t)):""===a.trim(e.val())?a.uniform.i18n("required",t):!0},a.uniform.validators.validateMinLength=function(e,t){var l=a.uniform.get_val("validateMinLength",e.attr("class"),0);return l>0&&l>e.val().length?a.uniform.i18n("minlength",t,l):!0},a.uniform.validators.validateMin=function(e,t){var l=a.uniform.get_val("validateMin",e.attr("class"),0);return l>parseInt(e.val(),10)?a.uniform.i18n("min",t,l):!0},a.uniform.validators.validateMaxLength=function(e,t){var l=a.uniform.get_val("validateMaxLength",e.attr("class"),0);return l>0&&e.val().length>l?a.uniform.i18n("maxlength",t,l):!0},a.uniform.validators.validateMax=function(e,t){var l=a.uniform.get_val("validateMax",e.attr("class"),0);return parseInt(e.val(),10)>l?a.uniform.i18n("max",t,l):!0},a.uniform.validators.validateSameAs=function(e,t,l){var n,r,s=e.attr("class").split(" "),i="",o="",u=e.closest("form");for(l=l||a.uniform.defaultOptions,r=0;s.length>r;r+=1)if("validateSameAs"===s[r]&&"undefined"!==s[r+1]){i=s[r+1];break}return i&&(n=u.find('input[name="'+i+'"]'),n.val()!==e.val())?(o=a.uniform.get_label_text(n,l),a.uniform.i18n("same_as",t,o)):!0},a.uniform.validators.validateEmail=function(e,t){return e.val().match(/^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/)?!0:a.uniform.i18n("email",t)},a.uniform.validators.validateUrl=function(e,t){return e.val().match(/^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_\-]*)(\.[A-Z0-9][A-Z0-9_\-]*)+)(:(\d+))?\/?/i)?!0:a.uniform.i18n("url",t)},a.uniform.validators.validateNumber=function(e,t){return e.val().match(/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/)||""===e.val()?!0:a.uniform.i18n("number",t)},a.uniform.validators.validateInteger=function(e,t){return e.val().match(/(^-?\d\d*$)/)||""===e.val()?!0:a.uniform.i18n("integer",t)},a.uniform.validators.validateAlpha=function(e,t){return e.val().match(/^[a-zA-Z]+$/)?!0:a.uniform.i18n("alpha",t)},a.uniform.validators.validateAlphaNum=function(e,t){return e.val().match(/\W/)?a.uniform.i18n("alphanum",t):!0},a.uniform.validators.validatePhrase=function(e,t){return""===e.val()||e.val().match(/^[\w\d\.\-_\(\)\*'# :,]+$/i)?!0:a.uniform.i18n("phrase",t)},a.uniform.validators.validatePhone=function(e,t){var l=/^\(?(\d{3})\)?[\- ]?(\d{3})[\- ]?(\d{4})$/;return l.test(e.val())?!0:a.uniform.i18n("phone",t)},a.uniform.validators.validateDate=function(e,t){return e.val().match("([0]?[1-9]|[1][0-2])/([0]?[1-9]|[1|2][0-9]|[3][0|1])/([0-9]{4}|[0-9]{2})$")?!0:a.uniform.i18n("date",t)},a.uniform.validators.validateCallback=function(e,t){var l,n=e.attr("class").split(" "),r="";for(l=0;n.length>l;l+=1)if("validateCallback"===n[l]&&"undefined"!==n[l+1]){r=n[l+1];break}return"undefined"!==window[r]&&"function"==typeof window[r]?window[r](e,t):a.uniform.i18n("callback",t,r)}}(jQuery); \ No newline at end of file +(function(a){a.uniform=function(){},a.uniform.get_val=function(a,e,t){var l,n=t;for(e=e.split(" "),l=0;e.length>l;l+=1)if(e[l]===a&&"undefined"!==e[l+1]&&"val-"===e[l+1].substr(0,4))return n=parseInt(e[l+1].substr(4),10);return n},a.uniform.get_label_text=function(e,t){var l=e.closest("label").text();return t=t||a.uniform.defaultOptions,""===l&&(l=e.closest("div."+t.holder_class).find("label").text()),l.replace("*","").replace(":","")},a.fn.uniform=function(e){return e=a.extend(a.uniform.defaultOptions,e),this.each(function(){var t,l,n,i,r,o;return t=a(this),l=[],n=a.proxy(a.uniform.get_label_text,this),i=a.proxy(a.uniform.get_val,this),r=a.proxy(a.uniform.validate,this),t.find(e.field_selector).each(function(){var t=a(this),l=t.val();t.data("default-color",t.css("color")),l!==t.data("default-value")&&l||(t.not("select").css("color",e.default_value_color),t.val(t.attr("data-default-value")))}),(e.ask_on_leave||t.hasClass("askOnLeave"))&&(o=t.serialize(),a(window).bind("beforeunload",function(){return o!==t.serialize()&&(e.ask_on_leave||t.hasClass("askOnLeave"))?a.isFunction(e.on_leave_callback)?e.on_leave_callback(t):window.confirm(a.uniform.i18n("on_leave")):void 0})),t.submit(function(){var l,n=!0;return t.removeClass("failedSubmit"),e.ask_on_leave=!1,t.removeClass("askOnLeave"),t.find(e.field_selector).each(function(){a(this).val()===a(this).data("default-value")&&a(this).val("")}),e.prevent_submit||t.hasClass("preventSubmit")?(t.find(e.field_selector).each(function(){a(this).blur()}),a.isFunction(e.submit_callback)&&(n=e.submit_callback(t)),(t.find("."+e.error_class).length||!n)&&(l=a.isFunction(e.prevent_submit_callback)?e.prevent_submit_callback(t,a.uniform.i18n("submit_msg"),[a.uniform.i18n("submit_help")]):a.uniform.showFormError(t,a.uniform.i18n("submit_msg"),[a.uniform.i18n("submit_help")]))):l=!0,a("#qunit-fixture").length&&(l=!1),l===!1&&t.addClass("failedSubmit"),l}),t.find(e.field_selector).on("focus",function(l){var n=a(this);window.console.log(l),t.find("."+e.focused_class).removeClass(e.focused_class),n.closest("."+e.holder_class).addClass(e.focused_class),n.val()===n.data("default-value")&&n.val(""),n.not("select").css("color",n.data("default-color"))}),t.find(e.field_selector).on("blur",function(){var l,i,r=a(this),o=!1,s=n(r,e);if(t.find("."+e.focused_class).removeClass(e.focused_class),(""===r.val()||r.val()===r.data("default-value"))&&!r.hasClass("required"))return r.not("select").css("color",e.default_value_color),r.val(r.data("default-value")),void 0;for(l in a.uniform.validators)if(r.hasClass(l)&&(i=a.uniform.validators[l](r,s,e),o=!0,"string"==typeof i))return r.trigger("uniform-error",i),void 0;o&&r.trigger("uniform-success"),r.css("color",r.data("default-color"))}),t.on("uniform-error",e.field_selector,function(t,n){a.uniform.showValidation(a(this),!1,n,l,e)}),t.on("uniform-success",e.field_selector,function(){a.uniform.showValidation(a(this),!0,"",l,e)}),a("input[autofocus]:first").trigger("focus"),this})},a.uniform.showFormError=function(e,t,l){var n,i;if(a("#errorMsg").length&&a("#errorMsg").remove(),i=a("
    ").attr("id","errorMsg").html("

    "+t+"

    "),l.length){i.append(a("
      "));for(n in l)l.hasOwnProperty(n)&&a("ol",i).append(a("
    1. ").text(l[n]))}return e.prepend(i),a("html, body").animate({scrollTop:e.offset().top},500),a("#errorMsg").slideDown(),!1},a.uniform.showFormSuccess=function(e,t){return a("#okMsg").remove(),e.prepend(a("
      ").attr("id","okMsg").html("

      "+t+"

      ")),a("html, body").animate({scrollTop:e.offset().top},500),a("#okMsg").slideDown(),!1},a.uniform.showValidation=function(e,t,l,n,i){var r,o;i=i||a.uniform.defaultOptions,r=e.closest("div."+i.holder_class).andSelf().toggleClass(i.error_class,!t).toggleClass(i.valid_class,t).find("p.form-hint"),o=e.attr("name"),t?o in n&&delete n[o]:n[o]=l,t||r.data("info-text")?t&&(l=r.data("info-text")):r.data("info-text",r.html()),l&&r.html(l)},a.uniform.i18n=function(e){var t,l,n=a.uniform.language[e],i=n.split("%"),r=i[0],o=/^([ds])(.*)$/;for(l=1;i.length>l;l+=1)t=o.exec(i[l]),t&&null!==arguments[l]&&("d"===t[1]?r+=parseInt(arguments[l],10):"s"===t[1]&&(r+=arguments[l]),r+=t[2]);return r},a.uniform.language={required:"%s is required",req_radio:"Please make a selection",req_checkbox:"You must select this checkbox to continue",minlength:"%s should be at least %d characters long",min:"%s should be greater than or equal to %d",maxlength:"%s should not be longer than %d characters",max:"%s should be less than or equal to %d",same_as:"%s is expected to be same as %s",email:"%s is not a valid email address",url:"%s is not a valid URL",number:"%s needs to be a number",integer:"%s needs to be a whole number",alpha:"%s should contain only letters (without special characters or numbers)",alphanum:"%s should contain only numbers and letters (without special characters)",phrase:"%s should contain only alphabetic characters, numbers, spaces, and the following: . , - _ () * # :",phone:"%s should be a phone number",date:"%s should be a date (mm/dd/yyyy)",callback:"Failed to validate %s field. Validator function (%s) is not defined!",on_leave:"Are you sure you want to leave this page without saving this form?",submit_msg:"Sorry, this form needs corrections.",submit_help:"Please see the items marked below.",submit_success:"Thank you, this form has been sent."},a.uniform.defaultOptions={submit_callback:!1,prevent_submit:!1,prevent_submit_callback:!1,ask_on_leave:!1,on_leave_callback:!1,valid_class:"valid",error_class:"error",focused_class:"focused",holder_class:"ctrl-holder",hint_class:"form-hint",field_selector:"input, textarea, select",default_value_color:"#afafaf"}})(jQuery),function(a){a.uniform=a.uniform||{},a.uniform.validators={},a.uniform.validators.required=function(e,t){var l;return e.is(":radio")?(l=e.attr("name"),a("input[name="+l+"]:checked").length?!0:a.uniform.i18n("req_radio",t)):e.is(":checkbox")?(l=e.attr("name"),e.is(":checked")?!0:a.uniform.i18n("req_checkbox",t)):""===a.trim(e.val())?a.uniform.i18n("required",t):!0},a.uniform.validators.validateMinLength=function(e,t){var l=a.uniform.get_val("validateMinLength",e.attr("class"),0);return l>0&&l>e.val().length?a.uniform.i18n("minlength",t,l):!0},a.uniform.validators.validateMin=function(e,t){var l=a.uniform.get_val("validateMin",e.attr("class"),0);return l>parseInt(e.val(),10)?a.uniform.i18n("min",t,l):!0},a.uniform.validators.validateMaxLength=function(e,t){var l=a.uniform.get_val("validateMaxLength",e.attr("class"),0);return l>0&&e.val().length>l?a.uniform.i18n("maxlength",t,l):!0},a.uniform.validators.validateMax=function(e,t){var l=a.uniform.get_val("validateMax",e.attr("class"),0);return parseInt(e.val(),10)>l?a.uniform.i18n("max",t,l):!0},a.uniform.validators.validateSameAs=function(e,t,l){var n,i,r=e.attr("class").split(" "),o="",s="",u=e.closest("form");for(l=l||a.uniform.defaultOptions,i=0;r.length>i;i+=1)if("validateSameAs"===r[i]&&"undefined"!==r[i+1]){o=r[i+1];break}return o&&(n=u.find('input[name="'+o+'"]'),n.val()!==e.val())?(s=a.uniform.get_label_text(n,l),a.uniform.i18n("same_as",t,s)):!0},a.uniform.validators.validateEmail=function(e,t){return e.val().match(/^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/)?!0:a.uniform.i18n("email",t)},a.uniform.validators.validateUrl=function(e,t){return e.val().match(/^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_\-]*)(\.[A-Z0-9][A-Z0-9_\-]*)+)(:(\d+))?\/?/i)?!0:a.uniform.i18n("url",t)},a.uniform.validators.validateNumber=function(e,t){return e.val().match(/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/)||""===e.val()?!0:a.uniform.i18n("number",t)},a.uniform.validators.validateInteger=function(e,t){return e.val().match(/(^-?\d\d*$)/)||""===e.val()?!0:a.uniform.i18n("integer",t)},a.uniform.validators.validateAlpha=function(e,t){return e.val().match(/^[a-zA-Z]+$/)?!0:a.uniform.i18n("alpha",t)},a.uniform.validators.validateAlphaNum=function(e,t){return e.val().match(/\W/)?a.uniform.i18n("alphanum",t):!0},a.uniform.validators.validatePhrase=function(e,t){return""===e.val()||e.val().match(/^[\w\d\.\-_\(\)\*'# :,]+$/i)?!0:a.uniform.i18n("phrase",t)},a.uniform.validators.validatePhone=function(e,t){var l=/^\(?(\d{3})\)?[\- ]?(\d{3})[\- ]?(\d{4})$/;return l.test(e.val())?!0:a.uniform.i18n("phone",t)},a.uniform.validators.validateDate=function(e,t){return e.val().match("([0]?[1-9]|[1][0-2])/([0]?[1-9]|[1|2][0-9]|[3][0|1])/([0-9]{4}|[0-9]{2})$")?!0:a.uniform.i18n("date",t)},a.uniform.validators.validateCallback=function(e,t){var l,n=e.attr("class").split(" "),i="";for(l=0;n.length>l;l+=1)if("validateCallback"===n[l]&&"undefined"!==n[l+1]){i=n[l+1];break}return"undefined"!==window[i]&&"function"==typeof window[i]?window[i](e,t):a.uniform.i18n("callback",t,i)}}(jQuery); \ No newline at end of file diff --git a/src/uni-form-validation.jquery.js b/src/uni-form-validation.jquery.js index 2f1cd5a..c51cf68 100644 --- a/src/uni-form-validation.jquery.js +++ b/src/uni-form-validation.jquery.js @@ -56,39 +56,6 @@ return text.replace('*', '').replace(':', ''); // Pretty formatting }; - // Set the results of form validation on the form element - $.uniform.validate = function ($input, isValid, errorMessage, errors, options) { - var $p, name; - options = options || $.uniform.defaultOptions; - $p = $input - .closest('div.' + options.holder_class) - .andSelf() - .toggleClass(options.error_class, !isValid) - .toggleClass(options.valid_class, isValid) - .find('p.form-hint'); - - name = $input.attr('name'); - - // Store this into the errors array, can be used by the custom callback - if (!isValid) { - errors[name] = errorMessage; - } - else if (name in errors) { - delete errors[name]; - } - - // If the validation failed we'll stash the p help text into the info-data - // and then put the error message in it's place. - if (!isValid && ! $p.data('info-text')) { - $p.data('info-text', $p.html()); - } - else if (isValid) { - errorMessage = $p.data('info-text'); - } - - if (errorMessage) { $p.html(errorMessage); } - }; - // Collection method will ppply the uniform behavior to elements $.fn.uniform = function (options) { @@ -129,6 +96,7 @@ if (options.ask_on_leave || $form.hasClass('askOnLeave')) { initial_values = $form.serialize(); $(window).bind("beforeunload", function () { + // We check options a second time so that we can disable this if ((initial_values !== $form.serialize()) && (options.ask_on_leave || $form.hasClass('askOnLeave')) ) { @@ -195,9 +163,7 @@ // QUnit needs to run this submit function, and still prevent the submit. // This isn't ideal, but it prevents us from having to trap events - if ($form.parents('#qunit-fixture').length) { - return_val = false; - } + if ($('#qunit-fixture').length) { return_val = false; } if (return_val === false) { $form.addClass('failedSubmit'); } @@ -206,9 +172,9 @@ // Set the form focus class and remove any classes other than the focus // class and then hide the default label text - $form.delegate(options.field_selector, 'focus', function () { + $form.find(options.field_selector).on('focus', function (e) { var $input = $(this); -window.console.log($input); +window.console.log(e); $form // Remove any other focus highlighting .find('.' + options.focused_class) .removeClass(options.focused_class); @@ -222,6 +188,7 @@ window.console.log($input); } $input.not('select').css('color', $input.data('default-color')); + }); // Validate a form field on the blur event @@ -230,7 +197,7 @@ window.console.log($input); // validators, and run them as we find them // // If the validators fail, we trigger either 'success' or 'error' events - $form.delegate(options.field_selector, 'blur', function () { + $form.find(options.field_selector).on('blur', function () { var $input = $(this), has_validation = false, validator, @@ -255,7 +222,7 @@ window.console.log($input); validation_result = $.uniform.validators[validator]($input, label, options); has_validation = true; if (typeof(validation_result) === 'string') { - $input.trigger('error', validation_result); + $input.trigger('uniform-error', validation_result); return; } } @@ -263,31 +230,30 @@ window.console.log($input); // If it had validation and we didn't return above, // then all validation passed - if (has_validation) { $input.trigger('success'); } + if (has_validation) { $input.trigger('uniform-success'); } // Return the color to the default $input.css('color', $input.data('default-color')); - return; - }); + }); // End Blur // Handle a validation error in the form element // This will set the field to have the error marker and update the // warning text - $form.delegate(options.field_selector, 'error', function (e, text) { - validate($(this), false, text, errors, options); + $form.on('uniform-error', options.field_selector, function (e, text) { + $.uniform.showValidation($(this), false, text, errors, options); }); // Handle a succesful validation in the form element // Remove any error messages and set the validation marker to be success - $form.delegate(options.field_selector, 'success', function () { - validate($(this), true, '', errors, options); + $form.on('uniform-success', options.field_selector, function () { + $.uniform.showValidation($(this), true, '', errors, options); }); - // Issue 9: HTML5 autofocus elements + // Issue 9: HTML5 autofocus element attribute // When the browser focuses, it happens before Uni-Form, and so we need // the manually run the focus event here to deal with style changes // and any handling of the default data - $('input[autofocus]:first').focus(); + $('input[autofocus]:first').trigger("focus"); return this; }); // end for each form @@ -333,6 +299,38 @@ window.console.log($input); return false; }; + // Set the results of form validation on the form element + $.uniform.showValidation = function ($input, isValid, errorMessage, errors, options) { + var $p, name; + options = options || $.uniform.defaultOptions; + $p = $input + .closest('div.' + options.holder_class) + .andSelf() + .toggleClass(options.error_class, !isValid) + .toggleClass(options.valid_class, isValid) + .find('p.form-hint'); + + name = $input.attr('name'); + + // Store this into the errors array, can be used by the custom callback + if (!isValid) { + errors[name] = errorMessage; + } + else if (name in errors) { + delete errors[name]; + } + + // If the validation failed we'll stash the p help text into the info-data + // and then put the error message in it's place. + if (!isValid && ! $p.data('info-text')) { + $p.data('info-text', $p.html()); + } + else if (isValid) { + errorMessage = $p.data('info-text'); + } + + if (errorMessage) { $p.html(errorMessage); } + }; // Simple replacement for i18n + sprintf // `$.uniform.i18n("string_key", sprintf style arguments)` diff --git a/test/issues.js b/test/issues.js index cee7e53..ca35718 100644 --- a/test/issues.js +++ b/test/issues.js @@ -72,16 +72,14 @@ prevent_submit_callback : function($submit_form) { hasError = $('input[name="color"]:radio:first', $submit_form) - .parents('div.ctrlHolder') + .parents('div.ctrl-holder') .hasClass('error'); return false; } }) .trigger('submit'); - equal( - hasError, - true, + equal(hasError, true, "Radio group has invalid class after submit" ); @@ -144,7 +142,7 @@ prevent_submit_callback : function($submit_form) { hasError = $('input[name="agreement"]:checkbox', $submit_form) - .parents('div.ctrlHolder') + .parents('div.ctrl-holder') .hasClass('error'); return false; } diff --git a/test/validation.js b/test/validation.js index 975be9e..410016c 100644 --- a/test/validation.js +++ b/test/validation.js @@ -51,9 +51,7 @@ * return bool result of assertion */ var validationTest = function (a, b, message) { - if (b === true) { - return ok((a === b), message); - } + if (b === true) { return ok((a === b), message); } return ok((typeof a === "string"), message); }; @@ -430,18 +428,15 @@ test("Default data hides correctly", function () { var default_text = 'This is a sample', - $input = $('#issue_15_a'), - $form = $('#qunit-form'); + $input = $('#issue_15_a'); $input.attr('data-default-value', default_text); - $form.uniform(); + $('#qunit-form').uniform(); // Should be showing the default equal($input.val(), default_text, "Initially display default data"); - - $input.focus(); // Should empty on focus + $input.trigger("focus"); // Should empty on focus equal($input.val(), '', "Hide default data on focus"); - });