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
19 KiB
11 lines
19 KiB
/*!
|
|
* # Semantic UI 2.2.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";t="undefined"!=typeof t&&t.Math==Math?t:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")(),e.fn.form=function(t){var i,a=e(this),o=a.selector||"",s=(new Date).getTime(),l=[],u=arguments[0],c=arguments[1],f="string"==typeof u,d=[].slice.call(arguments,1);return a.each(function(){var p,m,g,h,v,b,y,x,k,E,w,C,V,R,S,F,A,T,j=e(this),D=this,O=[],z=!1;T={initialize:function(){T.get.settings(),f?(A===r&&T.instantiate(),T.invoke(u)):(T.verbose("Initializing form validation",j,x),T.bindEvents(),T.set.defaults(),T.instantiate())},instantiate:function(){T.verbose("Storing instance of module",T),A=T,j.data(S,T)},destroy:function(){T.verbose("Destroying previous module",A),T.removeEvents(),j.removeData(S)},refresh:function(){T.verbose("Refreshing selector cache"),p=j.find(w.field),m=j.find(w.group),g=j.find(w.message),h=j.find(w.prompt),v=j.find(w.submit),b=j.find(w.clear),y=j.find(w.reset)},submit:function(){T.verbose("Submitting form",j),j.submit()},attachEvents:function(t,n){n=n||"submit",e(t).on("click"+F,function(e){T[n](),e.preventDefault()})},bindEvents:function(){T.verbose("Attaching form events"),j.on("submit"+F,T.validate.form).on("blur"+F,w.field,T.event.field.blur).on("click"+F,w.submit,T.submit).on("click"+F,w.reset,T.reset).on("click"+F,w.clear,T.clear),x.keyboardShortcuts&&j.on("keydown"+F,w.field,T.event.field.keydown),p.each(function(){var t=e(this),n=t.prop("type"),r=T.get.changeEvent(n,t);e(this).on(r+F,T.event.field.change)})},clear:function(){p.each(function(){var t=e(this),n=t.parent(),r=t.closest(m),i=r.find(w.prompt),a=t.data(E.defaultValue)||"",o=n.is(w.uiCheckbox),s=n.is(w.uiDropdown),l=r.hasClass(C.error);l&&(T.verbose("Resetting error on field",r),r.removeClass(C.error),i.remove()),s?(T.verbose("Resetting dropdown value",n,a),n.dropdown("clear")):o?t.prop("checked",!1):(T.verbose("Resetting field value",t,a),t.val(""))})},reset:function(){p.each(function(){var t=e(this),n=t.parent(),i=t.closest(m),a=i.find(w.prompt),o=t.data(E.defaultValue),s=n.is(w.uiCheckbox),l=n.is(w.uiDropdown),u=i.hasClass(C.error);o!==r&&(u&&(T.verbose("Resetting error on field",i),i.removeClass(C.error),a.remove()),l?(T.verbose("Resetting dropdown value",n,o),n.dropdown("restore defaults")):s?(T.verbose("Resetting checkbox value",n,o),t.prop("checked",o)):(T.verbose("Resetting field value",t,o),t.val(o)))})},is:{bracketedRule:function(e){return e.type&&e.type.match(x.regExp.bracket)},empty:function(e){return e&&0!==e.length?e.is('input[type="checkbox"]')?!e.is(":checked"):T.is.blank(e):!0},blank:function(t){return""===e.trim(t.val())},valid:function(){var t=!0;return T.verbose("Checking if form is valid"),e.each(k,function(e,n){T.validate.field(n,e)||(t=!1)}),t}},removeEvents:function(){j.off(F),p.off(F),v.off(F),p.off(F)},event:{field:{keydown:function(t){var n=e(this),r=t.which,i=n.is(w.input),a=n.is(w.checkbox),o=n.closest(w.uiDropdown).length>0,s={enter:13,escape:27};r==s.escape&&(T.verbose("Escape key pressed blurring field"),n.blur()),t.ctrlKey||r!=s.enter||!i||o||a||(z||(n.one("keyup"+F,T.event.field.keyup),T.submit(),T.debug("Enter pressed on input submitting form")),z=!0)},keyup:function(){z=!1},blur:function(t){var n=e(this),r=n.closest(m),i=T.get.validation(n);r.hasClass(C.error)?(T.debug("Revalidating field",n,i),i&&T.validate.field(i)):("blur"==x.on||"change"==x.on)&&i&&T.validate.field(i)},change:function(t){var n=e(this),r=n.closest(m),i=T.get.validation(n);("change"==x.on||r.hasClass(C.error)&&x.revalidate)&&(clearTimeout(T.timer),T.timer=setTimeout(function(){T.debug("Revalidating field",n,T.get.validation(n)),T.validate.field(i)},x.delay))}}},get:{ancillaryValue:function(e){return e.type&&T.is.bracketedRule(e)?e.type.match(x.regExp.bracket)[1]+"":!1},ruleName:function(e){return T.is.bracketedRule(e)?e.type.replace(e.type.match(x.regExp.bracket)[0],""):e.type},changeEvent:function(e,t){return"checkbox"==e||"radio"==e||"hidden"==e||t.is("select")?"change":T.get.inputEvent()},inputEvent:function(){return n.createElement("input").oninput!==r?"input":n.createElement("input").onpropertychange!==r?"propertychange":"keyup"},prompt:function(e,t){var n,r,i,a=T.get.ruleName(e),o=T.get.ancillaryValue(e),s=e.prompt||x.prompt[a]||x.text.unspecifiedRule,l=-1!==s.search("{value}"),u=-1!==s.search("{name}");return(u||l)&&(r=T.get.field(t.identifier)),l&&(s=s.replace("{value}",r.val())),u&&(n=r.closest(w.group).find("label").eq(0),i=1==n.length?n.text():r.prop("placeholder")||x.text.unspecifiedField,s=s.replace("{name}",i)),s=s.replace("{identifier}",t.identifier),s=s.replace("{ruleValue}",o),e.prompt||T.verbose("Using default validation prompt for type",s,a),s},settings:function(){if(e.isPlainObject(t)){var n,i=Object.keys(t),a=i.length>0?t[i[0]].identifier!==r&&t[i[0]].rules!==r:!1;a?(x=e.extend(!0,{},e.fn.form.settings,c),k=e.extend({},e.fn.form.settings.defaults,t),T.error(x.error.oldSyntax,D),T.verbose("Extending settings from legacy parameters",k,x)):(t.fields&&(n=Object.keys(t.fields),("string"==typeof t.fields[n[0]]||e.isArray(t.fields[n[0]]))&&e.each(t.fields,function(n,r){"string"==typeof r&&(r=[r]),t.fields[n]={rules:[]},e.each(r,function(e,r){t.fields[n].rules.push({type:r})})})),x=e.extend(!0,{},e.fn.form.settings,t),k=e.extend({},e.fn.form.settings.defaults,x.fields),T.verbose("Extending settings",k,x))}else x=e.fn.form.settings,k=e.fn.form.settings.defaults,T.verbose("Using default form validation",k,x);R=x.namespace,E=x.metadata,w=x.selector,C=x.className,V=x.error,S="module-"+R,F="."+R,A=j.data(S),T.refresh()},field:function(t){return T.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-"+E.validate+'="'+t+'"]').length>0?p.filter("[data-"+E.validate+'="'+t+'"]'):e("<input/>")},fields:function(t){var n=e();return e.each(t,function(e,t){n=n.add(T.get.field(t))}),n},validation:function(t){var n,r;return k?(e.each(k,function(e,i){r=i.identifier||e,T.get.field(r)[0]==t[0]&&(i.identifier=r,n=i)}),n||!1):!1},value:function(e){var t,n=[];return n.push(e),t=T.get.values.call(D,n),t[e]},values:function(t){var n=e.isArray(t)?T.get.fields(t):p,r={};return n.each(function(t,n){var i=e(n),a=(i.prop("type"),i.prop("name")),o=i.val(),s=i.is(w.checkbox),l=i.is(w.radio),u=-1!==a.indexOf("[]"),c=s?i.is(":checked"):!1;a&&(u?(a=a.replace("[]",""),r[a]||(r[a]=[]),s?c?r[a].push(o||!0):r[a].push(!1):r[a].push(o)):l?c&&(r[a]=o):s?c?r[a]=o||!0:r[a]=!1:r[a]=o)}),r}},has:{field:function(e){return T.verbose("Checking for existence of a field with identifier",e),"string"!=typeof e&&T.error(V.identifier,e),p.filter("#"+e).length>0?!0:p.filter('[name="'+e+'"]').length>0?!0:p.filter("[data-"+E.validate+'="'+e+'"]').length>0?!0:!1}},add:{prompt:function(t,n){var i=T.get.field(t),a=i.closest(m),o=a.children(w.prompt),s=0!==o.length;n="string"==typeof n?[n]:n,T.verbose("Adding field error state",t),a.addClass(C.error),x.inline&&(s||(o=x.templates.prompt(n),o.appendTo(a)),o.html(n[0]),s?T.verbose("Inline errors are disabled, no inline error added",t):x.transition&&e.fn.transition!==r&&j.transition("is supported")?(T.verbose("Displaying error with css transition",x.transition),o.transition(x.transition+" in",x.duration)):(T.verbose("Displaying error with fallback javascript animation"),o.fadeIn(x.duration)))},errors:function(e){T.debug("Adding form error messages",e),T.set.error(),g.html(x.templates.error(e))}},remove:{prompt:function(t){var n=T.get.field(t),i=n.closest(m),a=i.children(w.prompt);i.removeClass(C.error),x.inline&&a.is(":visible")&&(T.verbose("Removing prompt for field",t),x.transition&&e.fn.transition!==r&&j.transition("is supported")?a.transition(x.transition+" out",x.duration,function(){a.remove()}):a.fadeOut(x.duration,function(){a.remove()}))}},set:{success:function(){j.removeClass(C.error).addClass(C.success)},defaults:function(){p.each(function(){var t=e(this),n=t.filter(w.checkbox).length>0,r=n?t.is(":checked"):t.val();t.data(E.defaultValue,r)})},error:function(){j.removeClass(C.success).addClass(C.error)},value:function(e,t){var n={};return n[e]=t,T.set.values.call(D,n)},values:function(t){e.isEmptyObject(t)||e.each(t,function(t,n){var r,i=T.get.field(t),a=i.parent(),o=e.isArray(n),s=a.is(w.uiCheckbox),l=a.is(w.uiDropdown),u=i.is(w.radio)&&s,c=i.length>0;c&&(o&&s?(T.verbose("Selecting multiple",n,i),a.checkbox("uncheck"),e.each(n,function(e,t){r=i.filter('[value="'+t+'"]'),a=r.parent(),r.length>0&&a.checkbox("check")})):u?(T.verbose("Selecting radio value",n,i),i.filter('[value="'+n+'"]').parent(w.uiCheckbox).checkbox("check")):s?(T.verbose("Setting checkbox value",n,a),n===!0?a.checkbox("check"):a.checkbox("uncheck")):l?(T.verbose("Setting dropdown value",n,a),a.dropdown("set selected",n)):(T.verbose("Setting field value",n,i),i.val(n)))})}},validate:{form:function(e,t){var n=T.get.values();if(z)return!1;if(O=[],T.is.valid()){if(T.debug("Form has no validation errors, submitting"),T.set.success(),t!==!0)return x.onSuccess.call(D,e,n)}else if(T.debug("Form has errors"),T.set.error(),x.inline||T.add.errors(O),j.data("moduleApi")!==r&&e.stopImmediatePropagation(),t!==!0)return x.onFailure.call(D,O,n)},field:function(t,n){var i=t.identifier||n,a=T.get.field(i),o=t.depends?T.get.field(t.depends):!1,s=!0,l=[];return t.identifier||(T.debug("Using field name as identifier",i),t.identifier=i),a.prop("disabled")?(T.debug("Field is disabled. Skipping",i),s=!0):t.optional&&T.is.blank(a)?(T.debug("Field is optional and blank. Skipping",i),s=!0):t.depends&&T.is.empty(o)?(T.debug("Field depends on another value that is not present or empty. Skipping",o),s=!0):t.rules!==r&&e.each(t.rules,function(e,n){T.has.field(i)&&!T.validate.rule(t,n)&&(T.debug("Field is invalid",i,n.type),l.push(T.get.prompt(n,t)),s=!1)}),s?(T.remove.prompt(i,l),x.onValid.call(a),!0):(O=O.concat(l),T.add.prompt(i,l),x.onInvalid.call(a,l),!1)},rule:function(t,n){var i=T.get.field(t.identifier),a=(n.type,i.val()),o=T.get.ancillaryValue(n),s=T.get.ruleName(n),l=x.rules[s];return e.isFunction(l)?(a=a===r||""===a||null===a?"":e.trim(a+""),l.call(i,a,o)):void T.error(V.noRule,s)}},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,T,t);else{if(n===r)return T[t];T[t]=n}},debug:function(){!x.silent&&x.debug&&(x.performance?T.performance.log(arguments):(T.debug=Function.prototype.bind.call(console.info,console,x.name+":"),T.debug.apply(console,arguments)))},verbose:function(){!x.silent&&x.verbose&&x.debug&&(x.performance?T.performance.log(arguments):(T.verbose=Function.prototype.bind.call(console.info,console,x.name+":"),T.verbose.apply(console,arguments)))},error:function(){x.silent||(T.error=Function.prototype.bind.call(console.error,console,x.name+":"),T.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(T.performance.timer),T.performance.timer=setTimeout(T.performance.display,500)},display:function(){var t=x.name+":",n=0;s=!1,clearTimeout(T.performance.timer),e.each(l,function(e,t){n+=t["Execution Time"]}),t+=" "+n+"ms",o&&(t+=" '"+o+"'"),a.length>1&&(t+=" ("+a.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,a){var o,s,l,u=A;return n=n||d,a=D||a,"string"==typeof t&&u!==r&&(t=t.split(/[\. ]/),o=t.length-1,e.each(t,function(n,i){var a=n!=o?i+t[n+1].charAt(0).toUpperCase()+t[n+1].slice(1):t;if(e.isPlainObject(u[a])&&n!=o)u=u[a];else{if(u[a]!==r)return s=u[a],!1;if(!e.isPlainObject(u[i])||n==o)return u[i]!==r?(s=u[i],!1):!1;u=u[i]}})),e.isFunction(s)?l=s.apply(a,n):s!==r&&(l=s),e.isArray(i)?i.push(l):i!==r?i=[i,l]:l!==r&&(i=l),s}},T.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])?)*$/i,escape:/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,flags:/^\/(.*)\/(.*)?/,integer:/^\-?\d+$/,number:/^\-?\d*(\.\d+)?$/,url:/(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/i},text:{unspecifiedRule:"Please enter a valid value",unspecifiedField:"This field"},prompt:{empty:"{name} must have a value",checked:"{name} must be checked",email:"{name} must be a valid e-mail",url:"{name} must be a valid url",regExp:"{name} is not formatted correctly",integer:"{name} must be an integer",decimal:"{name} must be a decimal number",number:"{name} must be set to a number",is:'{name} must be "{ruleValue}"',isExactly:'{name} must be exactly "{ruleValue}"',not:'{name} cannot be set to "{ruleValue}"',notExactly:'{name} cannot be set to exactly "{ruleValue}"',contain:'{name} cannot contain "{ruleValue}"',containExactly:'{name} cannot contain exactly "{ruleValue}"',doesntContain:'{name} must contain "{ruleValue}"',doesntContainExactly:'{name} must contain exactly "{ruleValue}"',minLength:"{name} must be at least {ruleValue} characters",length:"{name} must be at least {ruleValue} characters",exactLength:"{name} must be exactly {ruleValue} characters",maxLength:"{name} cannot be longer than {ruleValue} characters",match:"{name} must match {ruleValue} field",different:"{name} must have a different value than {ruleValue} field",creditCard:"{name} must be a valid credit card number",minCount:"{name} must have at least {ruleValue} choices",exactCount:"{name} must have exactly {ruleValue} choices",maxCount:"{name} must have {ruleValue} or less choices"},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){return e.fn.form.settings.regExp.email.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,a,o,s=e.fn.form.settings.regExp.integer;return n&&-1===["",".."].indexOf(n)&&(-1==n.indexOf("..")?s.test(n)&&(i=a=n-0):(o=n.split("..",2),s.test(o[0])&&(i=o[0]-0),s.test(o[1])&&(a=o[1]-0))),s.test(t)&&(i===r||t>=i)&&(a===r||a>=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},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},creditCard:function(t,n){var r,i,a={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]}},o={},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=a[r],i&&(o={length:-1!==e.inArray(t.length,i.length),pattern:-1!==t.search(i.pattern)},o.length&&o.pattern&&(s=!0))}),!s))return!1;if(r={number:-1!==e.inArray(t.length,a.unionPay.length),pattern:-1!==t.search(a.unionPay.pattern)},r.number&&r.pattern)return!0;for(var u=t.length,c=0,f=[[0,1,2,3,4,5,6,7,8,9],[0,2,4,6,8,1,3,5,7,9]],d=0;u--;)d+=f[c][parseInt(t.charAt(u),10)],c^=1;return d%10===0&&d>0}},minCount:function(e,t){return 0==t?!0:1==t?""!==e:e.split(",").length>=t},exactCount:function(e,t){return 0==t?""===e:1==t?""!==e&&-1===e.search(","):e.split(",").length==t},maxCount:function(e,t){return 0==t?!1:1==t?-1===e.search(","):e.split(",").length<=t}}}}(jQuery,window,document);
|