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
16 KiB
11 lines
16 KiB
/*!
|
|
* # Semantic UI 2.1.0 - 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,r){"use strict";e.fn.form=function(t){var i,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,h,v,b,y,x,k,w,E,C,R,S,F,A,T,j,z=e(this),D=this,O=[],$=!1;j={initialize:function(){j.get.settings(),f?(T===r&&j.instantiate(),j.invoke(c)):(j.verbose("Initializing form validation",z,x),j.bindEvents(),j.set.defaults(),j.instantiate())},instantiate:function(){j.verbose("Storing instance of module",j),T=j,z.data(F,j)},destroy:function(){j.verbose("Destroying previous module",T),j.removeEvents(),z.removeData(F)},refresh:function(){j.verbose("Refreshing selector cache"),p=z.find(E.field),g=z.find(E.group),m=z.find(E.message),h=z.find(E.prompt),v=z.find(E.submit),b=z.find(E.clear),y=z.find(E.reset)},submit:function(){j.verbose("Submitting form",z),z.submit()},attachEvents:function(t,n){n=n||"submit",e(t).on("click"+A,function(e){j[n](),e.preventDefault()})},bindEvents:function(){j.verbose("Attaching form events"),z.on("submit"+A,j.validate.form).on("blur"+A,E.field,j.event.field.blur).on("click"+A,E.submit,j.submit).on("click"+A,E.reset,j.reset).on("click"+A,E.clear,j.clear),x.keyboardShortcuts&&z.on("keydown"+A,E.field,j.event.field.keydown),p.each(function(){var t=e(this),n=t.prop("type"),r=j.get.changeEvent(n,t);e(this).on(r+A,j.event.field.change)})},clear:function(){p.each(function(){var t=e(this),n=t.parent(),r=t.closest(g),i=r.find(E.prompt),o=t.data(w.defaultValue)||"",a=n.is(E.uiCheckbox),s=n.is(E.uiDropdown),l=r.hasClass(C.error);l&&(j.verbose("Resetting error on field",r),r.removeClass(C.error),i.remove()),s?(j.verbose("Resetting dropdown value",n,o),n.dropdown("clear")):a?t.prop("checked",!1):(j.verbose("Resetting field value",t,o),t.val(""))})},reset:function(){p.each(function(){var t=e(this),n=t.parent(),i=t.closest(g),o=i.find(E.prompt),a=t.data(w.defaultValue),s=n.is(E.uiCheckbox),l=n.is(E.uiDropdown),c=i.hasClass(C.error);a!==r&&(c&&(j.verbose("Resetting error on field",i),i.removeClass(C.error),o.remove()),l?(j.verbose("Resetting dropdown value",n,a),n.dropdown("restore defaults")):s?(j.verbose("Resetting checkbox value",n,a),t.prop("checked",a)):(j.verbose("Resetting field value",t,a),t.val(a)))})},is:{valid:function(){var t=!0;return j.verbose("Checking if form is valid"),e.each(k,function(e,n){j.validate.field(n)||(t=!1)}),t}},removeEvents:function(){z.off(A),p.off(A),v.off(A),p.off(A)},event:{field:{keydown:function(t){var n=e(this),r=t.which,i={enter:13,escape:27};r==i.escape&&(j.verbose("Escape key pressed blurring field"),n.blur()),!t.ctrlKey&&r==i.enter&&n.is(E.input)&&n.not(E.checkbox).length>0&&($||(n.one("keyup"+A,j.event.field.keyup),j.submit(),j.debug("Enter pressed on input submitting form")),$=!0)},keyup:function(){$=!1},blur:function(){var t=e(this),n=t.closest(g),r=j.get.validation(t);n.hasClass(C.error)?(j.debug("Revalidating field",t,r),j.validate.field(r)):("blur"==x.on||"change"==x.on)&&j.validate.field(r)},change:function(){var t=e(this),n=t.closest(g);("change"==x.on||n.hasClass(C.error)&&x.revalidate)&&(clearTimeout(j.timer),j.timer=setTimeout(function(){j.debug("Revalidating field",t,j.get.validation(t)),j.validate.field(j.get.validation(t))},x.delay))}}},get:{changeEvent:function(e,t){return"checkbox"==e||"radio"==e||"hidden"==e||t.is("select")?"change":j.get.inputEvent()},inputEvent:function(){return n.createElement("input").oninput!==r?"input":n.createElement("input").onpropertychange!==r?"propertychange":"keyup"},settings:function(){if(e.isPlainObject(t)){var n=Object.keys(t),i=n.length>0?t[n[0]].identifier!==r&&t[n[0]].rules!==r:!1;i?(x=e.extend(!0,{},e.fn.form.settings,u),k=e.extend({},e.fn.form.settings.defaults,t),j.error(x.error.oldSyntax,D),j.verbose("Extending settings from legacy parameters",k,x)):(x=e.extend(!0,{},e.fn.form.settings,t),k=e.extend({},e.fn.form.settings.defaults,x.fields),j.verbose("Extending settings",k,x))}else x=e.fn.form.settings,k=e.fn.form.settings.defaults,j.verbose("Using default form validation",k,x);S=x.namespace,w=x.metadata,E=x.selector,C=x.className,R=x.error,F="module-"+S,A="."+S,T=z.data(F),j.refresh()},field:function(t){return j.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(j.get.field(t))}),n},validation:function(t){var n;return k?(e.each(k,function(e,r){j.get.field(r.identifier)[0]==t[0]&&(n=r)}),n||!1):!1},value:function(e){var t,n=[];return n.push(e),t=j.get.values.call(D,n),t[e]},values:function(t){var n=e.isArray(t)?j.get.fields(t):p,r={};return n.each(function(t,n){var i=e(n),o=(i.prop("type"),i.prop("name")),a=i.val(),s=i.is(E.checkbox),l=i.is(E.radio),c=-1!==o.indexOf("[]"),u=s?i.is(":checked"):!1;o&&(c?(o=o.replace("[]",""),r[o]||(r[o]=[]),r[o].push(s?u?!0:!1:a)):l?u&&(r[o]=a):r[o]=s?u?!0:!1:a)}),r}},has:{field:function(e){return j.verbose("Checking for existence of a field with identifier",e),"string"!=typeof e&&j.error(R.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 i=j.get.field(t),o=i.closest(g),a=o.children(E.prompt),s=0!==a.length;n="string"==typeof n?[n]:n,j.verbose("Adding field error state",t),o.addClass(C.error),x.inline&&(s||(a=x.templates.prompt(n),a.appendTo(o)),a.html(n[0]),s?j.verbose("Inline errors are disabled, no inline error added",t):x.transition&&e.fn.transition!==r&&z.transition("is supported")?(j.verbose("Displaying error with css transition",x.transition),a.transition(x.transition+" in",x.duration)):(j.verbose("Displaying error with fallback javascript animation"),a.fadeIn(x.duration)))},errors:function(e){j.debug("Adding form error messages",e),m.html(x.templates.error(e))}},remove:{prompt:function(t){var n=j.get.field(t.identifier),i=n.closest(g),o=i.children(E.prompt);i.removeClass(C.error),x.inline&&o.is(":visible")&&(j.verbose("Removing prompt for field",t),x.transition&&e.fn.transition!==r&&z.transition("is supported")?o.transition(x.transition+" out",x.duration,function(){o.remove()}):o.fadeOut(x.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,r=n?t.is(":checked"):t.val();t.data(w.defaultValue,r)})},error:function(){z.removeClass(C.success).addClass(C.error)},value:function(e,t){var n={};return n[e]=t,j.set.values.call(D,n)},values:function(t){e.isEmptyObject(t)||e.each(t,function(t,n){var r,i=j.get.field(t),o=i.parent(),a=e.isArray(n),s=o.is(E.uiCheckbox),l=o.is(E.uiDropdown),c=i.is(E.radio)&&s,u=i.length>0;u&&(a&&s?(j.verbose("Selecting multiple",n,i),o.checkbox("uncheck"),e.each(n,function(e,t){r=i.filter('[value="'+t+'"]'),o=r.parent(),r.length>0&&o.checkbox("check")})):c?(j.verbose("Selecting radio value",n,i),i.filter('[value="'+n+'"]').parent(E.uiCheckbox).checkbox("check")):s?(j.verbose("Setting checkbox value",n,o),o.checkbox(n===!0?"check":"uncheck")):l?(j.verbose("Setting dropdown value",n,o),o.dropdown("set selected",n)):(j.verbose("Setting field value",n,i),i.val(n)))})}},validate:{form:function(e){return $?!1:(O=[],j.is.valid()?(j.debug("Form has no validation errors, submitting"),j.set.success(),x.onSuccess.call(D,e)):(j.debug("Form has errors"),j.set.error(),x.inline||j.add.errors(O),z.data("moduleApi")!==r&&e.stopImmediatePropagation(),x.onFailure.call(D,O)))},field:function(t){var n=j.get.field(t.identifier),i=!0,o=[];return n.prop("disabled")?(j.debug("Field is disabled. Skipping",t.identifier),i=!0):t.optional&&""===e.trim(n.val())?(j.debug("Field is optional and empty. Skipping",t.identifier),i=!0):t.rules!==r&&e.each(t.rules,function(e,n){j.has.field(t.identifier)&&!j.validate.rule(t,n)&&(j.debug("Field is invalid",t.identifier,n.type),o.push(n.prompt),i=!1)}),i?(j.remove.prompt(t,o),x.onValid.call(n),!0):(O=O.concat(o),j.add.prompt(t.identifier,o),x.onInvalid.call(n,o),!1)},rule:function(t,n){var i,o,a,s=j.get.field(t.identifier),l=n.type,c=s.val(),u=l.match(x.regExp.bracket),f=!0;if(c=c===r||""===c||null===c?"":e.trim(c+""),u){if(o=""+u[1],a=l.replace(u[0],""),i=x.rules[a],!e.isFunction(i))return void j.error(R.noRule,a);f=i.call(s,c,o)}else{if(i=x.rules[l],!e.isFunction(i))return void j.error(R.noRule,l);f=i.call(s,c)}return f}},setting:function(t,n){if(e.isPlainObject(t))e.extend(!0,x,t);else{if(n===r)return x[t];x[t]=n}},internal:function(t,n){if(e.isPlainObject(t))e.extend(!0,j,t);else{if(n===r)return j[t];j[t]=n}},debug:function(){x.debug&&(x.performance?j.performance.log(arguments):(j.debug=Function.prototype.bind.call(console.info,console,x.name+":"),j.debug.apply(console,arguments)))},verbose:function(){x.verbose&&x.debug&&(x.performance?j.performance.log(arguments):(j.verbose=Function.prototype.bind.call(console.info,console,x.name+":"),j.verbose.apply(console,arguments)))},error:function(){j.error=Function.prototype.bind.call(console.error,console,x.name+":"),j.error.apply(console,arguments)},performance:{log:function(e){var t,n,r;x.performance&&(t=(new Date).getTime(),r=s||t,n=t-r,s=t,l.push({Name:e[0],Arguments:[].slice.call(e,1)||"",Element:D,"Execution Time":n})),clearTimeout(j.performance.timer),j.performance.timer=setTimeout(j.performance.display,500)},display:function(){var t=x.name+":",n=0;s=!1,clearTimeout(j.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!==r||console.table!==r)&&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!==r&&(t=t.split(/[\. ]/),a=t.length-1,e.each(t,function(n,i){var o=n!=a?i+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]!==r)return s=c[o],!1;if(!e.isPlainObject(c[i])||n==a)return c[i]!==r?(s=c[i],!1):!1;c=c[i]}})),e.isFunction(s)?l=s.apply(o,n):s!==r&&(l=s),e.isArray(i)?i.push(l):i!==r?i=[i,l]:l!==r&&(i=l),s}},j.initialize()}),i!==r?i: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,decimal:/^\-?\d*(\.\d+)?$/,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])?",escape:/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,flags:/^\/(.*)\/(.*)?/,integer:/^\-?\d+$/,number:/^\-?\d*(\.\d+)?$/,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:{identifier:"You must specify a string identifier for each field",method:"The method you called is not defined.",noRule:"There is no rule matching the one you specified",oldSyntax:"Starting in 2.0 forms now only take a single settings object. Validation settings converted to new syntax automatically."},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 basic red pointing prompt label").html(t[0])}},rules:{empty:function(t){return!(t===r||""===t||e.isArray(t)&&0===t.length)},checked:function(){return e(this).filter(":checked").length>0},email:function(t){var n=new RegExp(e.fn.form.settings.regExp.email,"i");return n.test(t)},url:function(t){return e.fn.form.settings.regExp.url.test(t)},regExp:function(t,n){var r,i=n.match(e.fn.form.settings.regExp.flags);return i&&(n=i.length>=2?i[1]:n,r=i.length>=3?i[2]:""),t.match(new RegExp(n,r))},integer:function(t,n){var i,o,a,s=e.fn.form.settings.regExp.integer;return n===r||""===n||".."===n||(-1==n.indexOf("..")?s.test(n)&&(i=o=n-0):(a=n.split("..",2),s.test(a[0])&&(i=a[0]-0),s.test(a[1])&&(o=a[1]-0))),s.test(t)&&(i===r||t>=i)&&(o===r||o>=t)},decimal:function(t){return e.fn.form.settings.regExp.decimal.test(t)},number:function(t){return e.fn.form.settings.regExp.number.test(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},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},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))},doesntContain:function(t,n){return n=n.replace(e.fn.form.settings.regExp.escape,"\\$&"),-1===t.search(new RegExp(n,"i"))},doesntContainExactly:function(t,n){return n=n.replace(e.fn.form.settings.regExp.escape,"\\$&"),-1===t.search(new RegExp(n))},minLength:function(e,t){return e!==r?e.length>=t:!1},length:function(e,t){return e!==r?e.length>=t:!1},exactLength:function(e,t){return e!==r?e.length==t:!1},maxLength:function(e,t){return e!==r?e.length<=t:!1},match:function(t,n){{var i;e(this)}return e('[data-validate="'+n+'"]').length>0?i=e('[data-validate="'+n+'"]').val():e("#"+n).length>0?i=e("#"+n).val():e('[name="'+n+'"]').length>0?i=e('[name="'+n+'"]').val():e('[name="'+n+'[]"]').length>0&&(i=e('[name="'+n+'[]"]')),i!==r?t.toString()==i.toString():!1},creditCard:function(t,n){var r,i,o={visa:{pattern:/^4/,length:[16]},amex:{pattern:/^3[47]/,length:[15]},mastercard:{pattern:/^5[1-5]/,length:[16]},discover:{pattern:/^(6011|622(12[6-9]|1[3-9][0-9]|[2-8][0-9]{2}|9[0-1][0-9]|92[0-5]|64[4-9])|65)/,length:[16]},unionPay:{pattern:/^(62|88)/,length:[16,17,18,19]},jcb:{pattern:/^35(2[89]|[3-8][0-9])/,length:[16]},maestro:{pattern:/^(5018|5020|5038|6304|6759|676[1-3])/,length:[12,13,14,15,16,17,18,19]},dinersClub:{pattern:/^(30[0-5]|^36)/,length:[14]},laser:{pattern:/^(6304|670[69]|6771)/,length:[16,17,18,19]},visaElectron:{pattern:/^(4026|417500|4508|4844|491(3|7))/,length:[16]}},a={},s=!1,l="string"==typeof n?n.split(","):!1;if("string"==typeof t&&0!==t.length){if(l&&(e.each(l,function(n,r){i=o[r],i&&(a={length:-1!==e.inArray(t.length,i.length),pattern:-1!==t.search(i.pattern)},a.length&&a.pattern&&(s=!0))}),!s))return!1;if(r={number:-1!==e.inArray(t.length,o.unionPay.length),pattern:-1!==t.search(o.unionPay.pattern)},r.number&&r.pattern)return!0;for(var c=t.length,u=0,f=[[0,1,2,3,4,5,6,7,8,9],[0,2,4,6,8,1,3,5,7,9]],d=0;c--;)d+=f[u][parseInt(t.charAt(c),10)],u^=1;return d%10===0&&d>0}},different:function(t,n){{var i;e(this)}return e('[data-validate="'+n+'"]').length>0?i=e('[data-validate="'+n+'"]').val():e("#"+n).length>0?i=e("#"+n).val():e('[name="'+n+'"]').length>0?i=e('[name="'+n+'"]').val():e('[name="'+n+'[]"]').length>0&&(i=e('[name="'+n+'[]"]')),i!==r?t.toString()!==i.toString():!1},exactCount:function(e,t){return 0==t?""===e:1==t?""!==e&&-1===e.search(","):e.split(",").length==t},minCount:function(e,t){return 0==t?!0:1==t?""!==e:e.split(",").length>=t},maxCount:function(e,t){return 0==t?!1:1==t?-1===e.search(","):e.split(",").length<=t}}}}(jQuery,window,document);
|