You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

11 lines
14 KiB

/*!
* # Semantic UI 2.0.3 - Form Validation
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
!function(e,t,n,i){"use strict";e.fn.form=function(t){var r,o=e(this),a=o.selector||"",s=(new Date).getTime(),l=[],c=arguments[0],u=arguments[1],f="string"==typeof c,d=[].slice.call(arguments,1);return o.each(function(){var p,g,m,v,h,b,y,k,x,w,E,C,S,R,F,A,T,O,z=e(this),D=this,j=[],V=!1;O={initialize:function(){O.get.settings(),f?(T===i&&O.instantiate(),O.invoke(c)):(O.verbose("Initializing form validation",z,k),O.bindEvents(),O.set.defaults(),O.instantiate())},instantiate:function(){O.verbose("Storing instance of module",O),T=O,z.data(F,O)},destroy:function(){O.verbose("Destroying previous module",T),O.removeEvents(),z.removeData(F)},refresh:function(){O.verbose("Refreshing selector cache"),p=z.find(E.field),g=z.find(E.group),m=z.find(E.message),v=z.find(E.prompt),h=z.find(E.submit),b=z.find(E.clear),y=z.find(E.reset)},submit:function(){O.verbose("Submitting form",z),z.submit()},attachEvents:function(t,n){n=n||"submit",e(t).on("click"+A,function(e){O[n](),e.preventDefault()})},bindEvents:function(){O.verbose("Attaching form events"),z.on("submit"+A,O.validate.form).on("blur"+A,E.field,O.event.field.blur).on("click"+A,E.submit,O.submit).on("click"+A,E.reset,O.reset).on("click"+A,E.clear,O.clear),k.keyboardShortcuts&&z.on("keydown"+A,E.field,O.event.field.keydown),p.each(function(){var t=e(this),n=t.prop("type"),i=O.get.changeEvent(n,t);e(this).on(i+A,O.event.field.change)})},clear:function(){p.each(function(){var t=e(this),n=t.parent(),i=t.closest(g),r=i.find(E.prompt),o=t.data(w.defaultValue)||"",a=n.is(E.uiCheckbox),s=n.is(E.uiDropdown),l=i.hasClass(C.error);l&&(O.verbose("Resetting error on field",i),i.removeClass(C.error),r.remove()),s?(O.verbose("Resetting dropdown value",n,o),n.dropdown("clear")):a?t.prop("checked",!1):(O.verbose("Resetting field value",t,o),t.val(""))})},reset:function(){p.each(function(){var t=e(this),n=t.parent(),r=t.closest(g),o=r.find(E.prompt),a=t.data(w.defaultValue),s=n.is(E.uiCheckbox),l=n.is(E.uiDropdown),c=r.hasClass(C.error);a!==i&&(c&&(O.verbose("Resetting error on field",r),r.removeClass(C.error),o.remove()),l?(O.verbose("Resetting dropdown value",n,a),n.dropdown("restore defaults")):s?(O.verbose("Resetting checkbox value",n,a),t.prop("checked",a)):(O.verbose("Resetting field value",t,a),t.val(a)))})},is:{valid:function(){var t=!0;return O.verbose("Checking if form is valid"),e.each(x,function(e,n){O.validate.field(n)||(t=!1)}),t}},removeEvents:function(){z.off(A),p.off(A),h.off(A),p.off(A)},event:{field:{keydown:function(t){var n=e(this),i=t.which,r={enter:13,escape:27};i==r.escape&&(O.verbose("Escape key pressed blurring field"),n.blur()),!t.ctrlKey&&i==r.enter&&n.is(E.input)&&n.not(E.checkbox).length>0&&(V||(n.one("keyup"+A,O.event.field.keyup),O.submit(),O.debug("Enter pressed on input submitting form")),V=!0)},keyup:function(){V=!1},blur:function(){var t=e(this),n=t.closest(g),i=O.get.validation(t);n.hasClass(C.error)?(O.debug("Revalidating field",t,i),O.validate.field(i)):("blur"==k.on||"change"==k.on)&&O.validate.field(i)},change:function(){var t=e(this),n=t.closest(g);("change"==k.on||n.hasClass(C.error)&&k.revalidate)&&(clearTimeout(O.timer),O.timer=setTimeout(function(){O.debug("Revalidating field",t,O.get.validation(t)),O.validate.field(O.get.validation(t))},k.delay))}}},get:{changeEvent:function(e,t){return"checkbox"==e||"radio"==e||"hidden"==e||t.is("select")?"change":O.get.inputEvent()},inputEvent:function(){return n.createElement("input").oninput!==i?"input":n.createElement("input").onpropertychange!==i?"propertychange":"keyup"},settings:function(){if(e.isPlainObject(t)){var n=Object.keys(t),r=n.length>0?t[n[0]].identifier!==i:!1;r?(k=e.extend(!0,{},e.fn.form.settings,u),x=e.extend({},e.fn.form.settings.defaults,t),O.error(k.error.oldSyntax,D),O.verbose("Extending settings from legacy parameters",x,k)):(k=e.extend(!0,{},e.fn.form.settings,t),x=e.extend({},e.fn.form.settings.defaults,k.fields),O.verbose("Extending settings",x,k))}else k=e.fn.form.settings,x=e.fn.form.settings.defaults,O.verbose("Using default form validation",x,k);R=k.namespace,w=k.metadata,E=k.selector,C=k.className,S=k.error,F="module-"+R,A="."+R,T=z.data(F),O.refresh()},field:function(t){return O.verbose("Finding field with identifier",t),p.filter("#"+t).length>0?p.filter("#"+t):p.filter('[name="'+t+'"]').length>0?p.filter('[name="'+t+'"]'):p.filter('[name="'+t+'[]"]').length>0?p.filter('[name="'+t+'[]"]'):p.filter("[data-"+w.validate+'="'+t+'"]').length>0?p.filter("[data-"+w.validate+'="'+t+'"]'):e("<input/>")},fields:function(t){var n=e();return e.each(t,function(e,t){n=n.add(O.get.field(t))}),n},validation:function(t){var n;return x?(e.each(x,function(e,i){O.get.field(i.identifier)[0]==t[0]&&(n=i)}),n||!1):!1},value:function(e){var t,n=[];return n.push(e),t=O.get.values.call(D,n),t[e]},values:function(t){var n=e.isArray(t)?O.get.fields(t):p,i={};return n.each(function(t,n){var r=e(n),o=(r.prop("type"),r.prop("name")),a=r.val(),s=r.is(E.checkbox),l=r.is(E.radio),c=-1!==o.indexOf("[]"),u=s?r.is(":checked"):!1;if(o)if(c)if(o=o.replace("[]",""),i[o]||(i[o]=[]),s){if(!u)return O.debug("Omitted unchecked checkbox",r),!0;i[o].push(a)}else i[o].push(a);else if(l)u&&(i[o]=a);else if(s){if(!u)return O.debug("Omitted unchecked checkbox",r),!0;i[o]=!0}else i[o]=a}),i}},has:{field:function(e){return O.verbose("Checking for existence of a field with identifier",e),p.filter("#"+e).length>0?!0:p.filter('[name="'+e+'"]').length>0?!0:p.filter("[data-"+w.validate+'="'+e+'"]').length>0?!0:!1}},add:{prompt:function(t,n){var r=O.get.field(t),o=r.closest(g),a=o.children(E.prompt),s=0!==a.length;n="string"==typeof n?[n]:n,O.verbose("Adding field error state",t),o.addClass(C.error),k.inline&&(s||(a=k.templates.prompt(n),a.appendTo(o)),a.html(n[0]),s?O.verbose("Inline errors are disabled, no inline error added",t):k.transition&&e.fn.transition!==i&&z.transition("is supported")?(O.verbose("Displaying error with css transition",k.transition),a.transition(k.transition+" in",k.duration)):(O.verbose("Displaying error with fallback javascript animation"),a.fadeIn(k.duration)))},errors:function(e){O.debug("Adding form error messages",e),m.html(k.templates.error(e))}},remove:{prompt:function(t){var n=O.get.field(t.identifier),r=n.closest(g),o=r.children(E.prompt);r.removeClass(C.error),k.inline&&o.is(":visible")&&(O.verbose("Removing prompt for field",t),k.transition&&e.fn.transition!==i&&z.transition("is supported")?o.transition(k.transition+" out",k.duration,function(){o.remove()}):o.fadeOut(k.duration,function(){o.remove()}))}},set:{success:function(){z.removeClass(C.error).addClass(C.success)},defaults:function(){p.each(function(){var t=e(this),n=t.filter(E.checkbox).length>0,i=n?t.is(":checked"):t.val();t.data(w.defaultValue,i)})},error:function(){z.removeClass(C.success).addClass(C.error)},value:function(e,t){var n={};return n[e]=t,O.set.values.call(D,n)},values:function(t){e.isEmptyObject(t)||e.each(t,function(t,n){var i,r=O.get.field(t),o=r.parent(),a=e.isArray(n),s=o.is(E.uiCheckbox),l=o.is(E.uiDropdown),c=r.is(E.radio)&&s,u=r.length>0;u&&(a&&s?(O.verbose("Selecting multiple",n,r),o.checkbox("uncheck"),e.each(n,function(e,t){i=r.filter('[value="'+t+'"]'),o=i.parent(),i.length>0&&o.checkbox("check")})):c?(O.verbose("Selecting radio value",n,r),r.filter('[value="'+n+'"]').parent(E.uiCheckbox).checkbox("check")):s?(O.verbose("Setting checkbox value",n,o),o.checkbox(n===!0?"check":"uncheck")):l?(O.verbose("Setting dropdown value",n,o),o.dropdown("set selected",n)):(O.verbose("Setting field value",n,r),r.val(n)))})}},validate:{form:function(e){return V?!1:(j=[],O.is.valid()?(O.debug("Form has no validation errors, submitting"),O.set.success(),k.onSuccess.call(D,e)):(O.debug("Form has errors"),O.set.error(),k.inline||O.add.errors(j),z.data("moduleApi")!==i&&e.stopImmediatePropagation(),k.onFailure.call(D,j)))},field:function(t){var n=O.get.field(t.identifier),r=!0,o=[];return n.prop("disabled")?(O.debug("Field is disabled. Skipping",t.identifier),r=!0):t.optional&&""===e.trim(n.val())?(O.debug("Field is optional and empty. Skipping",t.identifier),r=!0):t.rules!==i&&e.each(t.rules,function(e,n){O.has.field(t.identifier)&&!O.validate.rule(t,n)&&(O.debug("Field is invalid",t.identifier,n.type),o.push(n.prompt),r=!1)}),r?(O.remove.prompt(t,o),k.onValid.call(n),!0):(j=j.concat(o),O.add.prompt(t.identifier,o),k.onInvalid.call(n,o),!1)},rule:function(t,n){var i,r,o,a=O.get.field(t.identifier),s=n.type,l=a.val(),c=s.match(k.regExp.bracket),u=!0;if(l=e.trim(a.val()+""),c){if(r=""+c[1],o=s.replace(c[0],""),i=k.rules[o],!e.isFunction(i))return void O.error(S.noRule,o);u=i.call(a,l,r)}else{if(i=k.rules[s],!e.isFunction(i))return void O.error(S.noRule,s);u=i.call(a,l)}return u}},setting:function(t,n){if(e.isPlainObject(t))e.extend(!0,k,t);else{if(n===i)return k[t];k[t]=n}},internal:function(t,n){if(e.isPlainObject(t))e.extend(!0,O,t);else{if(n===i)return O[t];O[t]=n}},debug:function(){k.debug&&(k.performance?O.performance.log(arguments):(O.debug=Function.prototype.bind.call(console.info,console,k.name+":"),O.debug.apply(console,arguments)))},verbose:function(){k.verbose&&k.debug&&(k.performance?O.performance.log(arguments):(O.verbose=Function.prototype.bind.call(console.info,console,k.name+":"),O.verbose.apply(console,arguments)))},error:function(){O.error=Function.prototype.bind.call(console.error,console,k.name+":"),O.error.apply(console,arguments)},performance:{log:function(e){var t,n,i;k.performance&&(t=(new Date).getTime(),i=s||t,n=t-i,s=t,l.push({Name:e[0],Arguments:[].slice.call(e,1)||"",Element:D,"Execution Time":n})),clearTimeout(O.performance.timer),O.performance.timer=setTimeout(O.performance.display,500)},display:function(){var t=k.name+":",n=0;s=!1,clearTimeout(O.performance.timer),e.each(l,function(e,t){n+=t["Execution Time"]}),t+=" "+n+"ms",a&&(t+=" '"+a+"'"),o.length>1&&(t+=" ("+o.length+")"),(console.group!==i||console.table!==i)&&l.length>0&&(console.groupCollapsed(t),console.table?console.table(l):e.each(l,function(e,t){console.log(t.Name+": "+t["Execution Time"]+"ms")}),console.groupEnd()),l=[]}},invoke:function(t,n,o){var a,s,l,c=T;return n=n||d,o=D||o,"string"==typeof t&&c!==i&&(t=t.split(/[\. ]/),a=t.length-1,e.each(t,function(n,r){var o=n!=a?r+t[n+1].charAt(0).toUpperCase()+t[n+1].slice(1):t;if(e.isPlainObject(c[o])&&n!=a)c=c[o];else{if(c[o]!==i)return s=c[o],!1;if(!e.isPlainObject(c[r])||n==a)return c[r]!==i?(s=c[r],!1):!1;c=c[r]}})),e.isFunction(s)?l=s.apply(o,n):s!==i&&(l=s),e.isArray(r)?r.push(l):r!==i?r=[r,l]:l!==i&&(r=l),s}},O.initialize()}),r!==i?r:this},e.fn.form.settings={name:"Form",namespace:"form",debug:!1,verbose:!1,performance:!0,fields:!1,keyboardShortcuts:!0,on:"submit",inline:!1,delay:200,revalidate:!0,transition:"scale",duration:200,onValid:function(){},onInvalid:function(){},onSuccess:function(){return!0},onFailure:function(){return!1},metadata:{defaultValue:"default",validate:"validate"},regExp:{bracket:/\[(.*)\]/i,escape:/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,email:"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?",integer:/^\-?\d+$/,flags:/^\/(.*)\/(.*)?/,url:/(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/i},selector:{checkbox:'input[type="checkbox"], input[type="radio"]',clear:".clear",field:"input, textarea, select",group:".field",input:"input",message:".error.message",prompt:".prompt.label",radio:'input[type="radio"]',reset:'.reset:not([type="reset"])',submit:'.submit:not([type="submit"])',uiCheckbox:".ui.checkbox",uiDropdown:".ui.dropdown"},className:{error:"error",label:"ui prompt label",pressed:"down",success:"success"},error:{oldSyntax:"Starting in 2.0 forms now only take a single settings object. Validation settings converted to new syntax automatically.",noRule:"There is no rule matching the one you specified",method:"The method you called is not defined."},templates:{error:function(t){var n='<ul class="list">';return e.each(t,function(e,t){n+="<li>"+t+"</li>"}),n+="</ul>",e(n)},prompt:function(t){return e("<div/>").addClass("ui red pointing prompt label").html(t[0])}},rules:{checked:function(){return e(this).filter(":checked").length>0},contains:function(t,n){return n=n.replace(e.fn.form.settings.regExp.escape,"\\$&"),-1!==t.search(new RegExp(n,"i"))},containsExactly:function(t,n){return n=n.replace(e.fn.form.settings.regExp.escape,"\\$&"),-1!==t.search(new RegExp(n))},email:function(t){var n=new RegExp(e.fn.form.settings.regExp.email,"i");return n.test(t)},empty:function(t){return!(t===i||""===t||e.isArray(t)&&0===t.length)},integer:function(t,n){var r,o,a,s=e.fn.form.settings.regExp.integer;return n===i||""===n||".."===n||(-1==n.indexOf("..")?s.test(n)&&(r=o=n-0):(a=n.split("..",2),s.test(a[0])&&(r=a[0]-0),s.test(a[1])&&(o=a[1]-0))),s.test(t)&&(r===i||t>=r)&&(o===i||o>=t)},is:function(e,t){return t="string"==typeof t?t.toLowerCase():t,e="string"==typeof e?e.toLowerCase():e,e==t},isExactly:function(e,t){return e==t},length:function(e,t){return e!==i?e.length>=t:!1},different:function(t,n){{var r;e(this)}return e('[data-validate="'+n+'"]').length>0?r=e('[data-validate="'+n+'"]').val():e("#"+n).length>0?r=e("#"+n).val():e('[name="'+n+'"]').length>0?r=e('[name="'+n+'"]').val():e('[name="'+n+'[]"]').length>0&&(r=e('[name="'+n+'[]"]')),r!==i?t.toString()!==r.toString():!1},match:function(t,n){{var r;e(this)}return e('[data-validate="'+n+'"]').length>0?r=e('[data-validate="'+n+'"]').val():e("#"+n).length>0?r=e("#"+n).val():e('[name="'+n+'"]').length>0?r=e('[name="'+n+'"]').val():e('[name="'+n+'[]"]').length>0&&(r=e('[name="'+n+'[]"]')),r!==i?t.toString()==r.toString():!1},maxCount:function(t,n){return t=t.split(","),e.isArray(t)&&t.length<=n},exactCount:function(t,n){return t=t.split(","),e.isArray(t)&&t.length==n},minCount:function(t,n){return t=t.split(","),e.isArray(t)&&t.length>=n},regExp:function(t,n){var i,r=n.match(e.fn.form.settings.regExp.flags);return r&&(n=r.length>=2?r[1]:n,i=r.length>=3?r[2]:""),t.match(new RegExp(n,i))},maxLength:function(e,t){return e!==i?e.length<=t:!1},not:function(e,t){return e="string"==typeof e?e.toLowerCase():e,t="string"==typeof t?t.toLowerCase():t,e!=t},notExactly:function(e,t){return e!=t},url:function(t){return e.fn.form.settings.regExp.url.test(t)}}}}(jQuery,window,document);