@jdlien/validator 1.3.3 → 1.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -157,9 +157,11 @@ function customValidationPromise(value) {
157
157
 
158
158
  ## Displaying Error Messages
159
159
 
160
- Validator will display error messages in the divs with the id of the input + `-error`. For example, if the input id is `inputid`, the error message will be displayed in the div with the id `inputid-error`. If this finds nothing, Validator will fall back to looking for an input with an id of the input's name + `-error`, and if that finds nothing, it will attempt to use the `aria-describedby` value of the input. You will need to create these divs in your HTML. They should initially be hidden with a class that sets properties such as `display: none;`, `visibility: hidden;`, or `opacity: 0;`.
160
+ It is recommended to create an error message element (likely a div) with a unique id and then use its id in an `aria-describedby` attribute in each associated input. This will ensure that Validator knows exactly what error element is associated with each input, and this works seamlessly for groups of inputs, like radio buttons. This will also confer improved accessibility and allow screen readers to announce the error message when the input is focused.
161
161
 
162
- Additionally, it is a good practice to add an `aria-describedby` attribute to each input that references the error message div's id. If all else fails, such as in the case of multiple checkbox/radio elements, Validator can use this to associate the error element to the input or input group. This will also allow screen readers to announce the error message when the input is focused.
162
+ If you do not use `aria-describedby`, Validator will fall back to displaying error messages in the first element having the id or name of the input + `-error`. For example, if the input id is `inputid`, the error message will be displayed in the div with the id `inputid-error`.
163
+
164
+ It is recommended to initially hide error elements with a class that sets properties such as `display: none;`, `visibility: hidden;`, or `opacity: 0;`.
163
165
 
164
166
  You can customize the class(es) that Validator uses to hide the error messages by passing in a `hideErrorClass` option to the Validator constructor. The default is `hidden opacity-0`.
165
167
 
package/dist/validator.js CHANGED
@@ -1 +1 @@
1
- (function(E,f){typeof exports=="object"&&typeof module<"u"?module.exports=f():typeof define=="function"&&define.amd?define(f):(E=typeof globalThis<"u"?globalThis:E||self,E.Validator=f())})(this,function(){"use strict";var ae=Object.defineProperty;var se=(E,f,o)=>f in E?ae(E,f,{enumerable:!0,configurable:!0,writable:!0,value:o}):E[f]=o;var m=(E,f,o)=>(se(E,typeof f!="symbol"?f+"":f,o),o);var E=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},f={exports:{}};(function(M,t){(function(r,n){n(t)})(E,function(r){function n(e){return e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement}function l(e,s){typeof s=="string"&&(s=[s]);const a=e.dataset.type||"",i=e.type;return!!(s.includes(a)||s.includes(i))}function g(e){return e.replace(/YYYY/g,"Y").replace(/YY/g,"y").replace(/MMMM/g,"F").replace(/MMM/g,"{3}").replace(/MM/g,"{2}").replace(/M/g,"n").replace(/DD/g,"{5}").replace(/D/g,"j").replace(/dddd/g,"l").replace(/ddd/g,"D").replace(/dd/g,"D").replace(/d/g,"w").replace(/HH/g,"{6}").replace(/H/g,"G").replace(/hh/g,"h").replace(/mm/g,"i").replace(/m/g,"i").replace(/ss/g,"S").replace(/s/g,"s").replace(/A/gi,"K").replace(/\{3\}/g,"M").replace(/\{2\}/g,"m").replace(/\{5\}/g,"d").replace(/\{6\}/g,"H")}function v(e){const s=parseInt(e);if(typeof e=="number"||!isNaN(s))return s-1;const a=new Date(`1 ${e} 2000`).getMonth();if(!isNaN(a))return a;const i={ja:0,en:0,fe:1,fé:1,ap:3,ab:3,av:3,mai:4,juin:5,juil:6,au:7,ag:7,ao:7,se:8,o:9,n:10,d:11};for(const h in i)if(e.toLowerCase().startsWith(h))return i[h];throw new Error("Invalid month name: "+e)}function L(e){return typeof e=="string"&&(e=parseInt(e.replace(/\D/g,""))),e>99?e:e<(new Date().getFullYear()+20)%100?e+2e3:e+1900}function w(e){if(e instanceof Date)return e;e=e.trim().toLowerCase();let s=0,a=0,i=0,h=0,d=0,u=0;const p=new RegExp(/\d{1,2}\:\d\d(?:\:\d\ds?)?\s?(?:[a|p]m?)?/gi);if(p.test(e)){const R=e.match(p)[0];e=e.replace(R,"").trim();const y=T(R);if(y!==null&&({hour:h,minute:d,second:u}=y),e.length<=2){const C=new Date;return new Date(C.getFullYear(),C.getMonth(),C.getDate(),h,d,u)}}const b=/(^|\b)(mo|tu|we|th|fr|sa|su|lu|mard|mer|jeu|ve|dom)[\w]*\.?/gi;e=e.replace(b,"").trim();const c=new Date(new Date().setHours(0,0,0,0));if(/(now|today)/.test(e))return c;if(e.includes("tomorrow"))return new Date(c.setDate(c.getDate()+1));e.length===8&&(e=e.replace(/(\d\d\d\d)(\d\d)(\d\d)/,"$1-$2-$3")),e.length===6&&(e=e.replace(/(\d\d)(\d\d)(\d\d)/,L(e.slice(0,2))+"-$2-$3"));try{({year:s,month:a,day:i}=O(e))}catch{return new Date("")}return new Date(s,a-1,i,h,d,u)}function k(e,s=[null,null,null]){const a=i=>i.filter(h=>!s.includes(h));return e===0||e>31?a(["y"]):e>12?a(["d","y"]):e>=1&&e<=12?a(["m","d","y"]):[]}function O(e){const s=e.split(/[\s-/:.,]+/).filter(d=>d!=="");if(s.length<3){if(e.match(/\d{4}/)!==null)throw new Error("Invalid Date");s.unshift(String(new Date().getFullYear()))}const a={year:0,month:0,day:0};function i(d,u){d==="year"?a.year=L(u):a[d]=u}let h=0;for(;!(a.year&&a.month&&a.day);){e:for(const d of s){if(h++,/^[a-zA-Zé]+$/.test(d)){a.month||i("month",v(d)+1);continue}if(/^'\d\d$/.test(d)||/^\d{3,5}$/.test(d)){a.year||i("year",parseInt(d.replace(/'/,"")));continue}const u=parseInt(d);if(isNaN(u))throw console.error(`not date because ${d} isNaN`),new Error("Invalid Date");const p=k(u,[a.year?"y":null,a.month?"m":null,a.day?"d":null]);if(p.length==1){if(p[0]==="m"&&!a.month){i("month",u);continue e}if(p[0]==="d"&&!a.day){i("day",u);continue e}if(p[0]==="y"&&!a.year){i("year",u);continue e}}h>3&&(!a.month&&p.includes("m")?i("month",u):!a.day&&p.includes("d")&&i("day",u))}if(h>6)throw new Error("Invalid Date")}if(a.year&&a.month&&a.day)return a;throw new Error("Invalid Date")}function T(e){if(e=e.trim().toLowerCase(),e==="now"){const c=new Date;return{hour:c.getHours(),minute:c.getMinutes(),second:c.getSeconds()}}const s=e.match(/(\d{3,4})/);if(s){const c=s[1].length,R=s[1].slice(0,c==3?1:2),y=s[1].slice(-2);e=e.replace(s[1],R+":"+y)}const a=new RegExp(/^(\d{1,2})(?::(\d{1,2}))?\s*(?:(a|p)m?)?$/i);if(a.test(e)){const c=e.match(a);if(c===null)return null;e=c[1]+":"+(c[2]||"00")+(c[3]||"")}const i=new RegExp(/^(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?\s*(?:(a|p)m?)?$/i);if(!i.test(e))return null;const h=e.match(i);if(h===null)return null;const d=parseInt(h[1]),u=parseInt(h[2]),p=h[3]?parseInt(h[3]):0,b=h[4];return isNaN(d)||isNaN(u)||isNaN(p)?null:b==="p"&&d<12?{hour:d+12,minute:u,second:p}:b==="a"&&d===12?{hour:0,minute:u,second:p}:d<0||d>23||u<0||u>59||p<0||p>59?null:{hour:d,minute:u,second:p}}function _(e,s="h:mm A"){const a=T(e);if(a){const i=new Date;return i.setHours(a.hour),i.setMinutes(a.minute),i.setSeconds(a.second),i.setMilliseconds(0),S(i,s)}return""}function S(e,s="YYYY-MM-DD"){if(e=w(e),isNaN(e.getTime()))return"";const a={y:e.getFullYear(),M:e.getMonth(),D:e.getDate(),W:e.getDay(),H:e.getHours(),m:e.getMinutes(),s:e.getSeconds(),ms:e.getMilliseconds()},i=(c,R=2)=>(c+"").padStart(R,"0"),h=()=>a.H%12||12,d=c=>c<12?"AM":"PM",u=c=>"January|February|March|April|May|June|July|August|September|October|November|December".split("|")[c];function p(c,R=0){const y="Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday".split("|");return R?y[c].slice(0,R):y[c]}const b={YY:String(a.y).slice(-2),YYYY:a.y,M:a.M+1,MM:i(a.M+1),MMMM:u(a.M),MMM:u(a.M).slice(0,3),D:String(a.D),DD:i(a.D),d:String(a.W),dd:p(a.W,2),ddd:p(a.W,3),dddd:p(a.W),H:String(a.H),HH:i(a.H),h:h(),hh:i(h()),A:d(a.H),a:d(a.H).toLowerCase(),m:String(a.m),mm:i(a.m),s:String(a.s),ss:i(a.s),SSS:i(a.ms,3)};return s.replace(/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,(c,R)=>R||b[c])}function x(e,s){const a=w(e);return isNaN(a.getTime())?"":((!s||s.length===0)&&(s="YYYY-MMM-DD"),S(a,s))}function $(e){if(typeof e!="string"&&!(e instanceof Date))return!1;let s=w(e);return s==null?!1:!isNaN(s.getTime())}function V(e,s){return!(s==="past"&&e>new Date||s==="future"&&e.getTime()<new Date().setHours(0,0,0,0))}function Y(e){let s=T(e);return s===null?!1:!isNaN(s.hour)&&!isNaN(s.minute)&&!isNaN(s.second)}function P(e){if(e.length>255||!new RegExp(/^.+@.+\.[a-zA-Z0-9]{2,}$/).test(e))return!1;let s="";return s+="^([a-zA-Z0-9!#$%'*+/=?^_`{|}~-]+",s+="(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*",s+="|",s+='"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*"',s+=")@(",s+="(",s+="(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+",s+="[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?",s+=")",s+=")$",new RegExp(s).test(e)}function U(e){return e=e.replace(/^[^2-90]+/g,""),e=e.replace(/(\d\d\d).*?(\d\d\d).*?(\d\d\d\d)(.*)/,"$1-$2-$3$4"),e}function F(e){return/^\d\d\d-\d\d\d-\d\d\d\d$/.test(e)}function q(e){return e.replace(/[^0-9]/g,"")}function Z(e){return/^\-?\d*\.?\d*$/.test(e)}function z(e){return e.replace(/[^\-0-9.]/g,"").replace(/(^-)|(-)/g,(s,a)=>a?"-":"").replace(/(\..*)\./g,"$1")}function G(e){return/^\-?\d*$/.test(e)}function j(e){return e=e.trim(),new RegExp("^(?:[a-z+]+:)?//","i").test(e)?e:"https://"+e}function K(e){return new RegExp("^(?:[-a-z+]+:)?//","i").test(e)}function B(e){return e=e.replace(/[^0-9]/g,"").replace(/(.{5})(.*)/,"$1-$2").trim(),e.length===6&&(e=e.replace(/-/,"")),e}function W(e){return new RegExp(/^\d{5}(-\d{4})?$/).test(e)}function J(e){return e=e.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/(.{3})\s*(.*)/,"$1 $2").trim(),e}function Q(e){return new RegExp(/^[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ] ?[0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]$/).test(e)}function X(e){return["transparent","currentColor"].includes(e)?!0:typeof e!="string"||!e.trim()?!1:typeof CSS=="object"&&typeof CSS.supports=="function"?CSS.supports("color",e):ee(e)}function ee(e){const s=new RegExp(/^rgba?\(\s*(\d{1,3}%?,\s*){2}\d{1,3}%?\s*(?:,\s*(\.\d+|0+(\.\d+)?|1(\.0+)?|0|1\.0|\d{1,2}(\.\d*)?%|100%))?\s*\)$/),a=new RegExp(/^hsla?\(\s*\d+(deg|grad|rad|turn)?,\s*\d{1,3}%,\s*\s*\d{1,3}%(?:,\s*(\.\d+|0+(\.\d+)?|1(\.0+)?|0|1\.0|\d{1,2}(\.\d*)?%|100%))?\s*\)$/),i=new RegExp(/^rgba?\(\s*(\d{1,3}%?\s+){2}\d{1,3}%?\s*(?:\s*\/\s*(\.\d+|0+(\.\d+)?|1(\.0+)?|0|1\.0|\d{1,2}(\.\d*)?%|100%))?\s*\)$/),h=new RegExp(/^hsla?\(\s*\d+(deg|grad|rad|turn)?\s+\d{1,3}%\s+\s*\d{1,3}%(?:\s*\/\s*(\.\d+|0+(\.\d+)?|1(\.0+)?|0|1\.0|\d{1,2}(\.\d*)?%|100%))?\s*\)$/),d=new RegExp(/^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);let u="aliceblue|antiquewhite|aqua|aquamarine|azure|beige|bisque|black|blanchedalmond|blue|blueviolet|brown|burlywood|cadetblue|chartreuse|chocolate|coral|cornflowerblue|cornsilk|crimson|cyan|darkblue|darkcyan|darkgoldenrod|darkgray|darkgreen|darkgrey|darkkhaki|darkmagenta|darkolivegreen|darkorange|darkorchid|darkred|darksalmon|darkseagreen|darkslateblue|darkslategray|darkslategrey|darkturquoise|darkviolet|deeppink|deepskyblue|dimgray|dimgrey|dodgerblue|firebrick|floralwhite|forestgreen|fuchsia|gainsboro|ghostwhite|gold|goldenrod|gray|green|greenyellow|grey|honeydew|hotpink|indianred|indigo|ivory|khaki|lavender|lavenderblush|lawngreen|lemonchiffon|lightblue|lightcoral|lightcyan|lightgoldenrodyellow|lightgray|lightgreen|lightgrey|lightpink|lightsalmon|lightseagreen|lightskyblue|lightslategray|lightslategrey|lightsteelblue|lightyellow|lime|limegreen|linen|magenta|maroon|mediumaquamarine|mediumblue|mediumorchid|mediumpurple|mediumseagreen|mediumslateblue|mediumspringgreen|mediumturquoise|mediumvioletred|midnightblue|mintcream|mistyrose|moccasin|navajowhite|navy|oldlace|olive|olivedrab|orange|orangered|orchid|palegoldenrod|palegreen|paleturquoise|palevioletred|papayawhip|peachpuff|peru|pink|plum|powderblue|purple|rebeccapurple|red|rosybrown|royalblue|saddlebrown|salmon|sandybrown|seagreen|seashell|sienna|silver|skyblue|slateblue|slategray|slategrey|snow|springgreen|steelblue|tan|teal|thistle|tomato|turquoise|violet|wheat|white|whitesmoke|yellow|yellowgreen";const p=new RegExp(`^(${u})$`,"i");return s.test(e)||a.test(e)||i.test(e)||h.test(e)||d.test(e)||p.test(e)}let I=null;const D=new Map;function te(e){if(e=e.trim().toLowerCase(),["transparent","currentcolor"].includes(e))return e;if(D.has(e))return D.get(e);I===null&&(I=document.createElement("canvas"),I.willReadFrequently=!0);let s=I.getContext("2d");if(!s)throw new Error("Can't get context from colorCanvas");s.fillStyle=e,s.fillRect(0,0,1,1);let a=s.getImageData(0,0,1,1).data,i="#"+("000000"+(a[0]<<16|a[1]<<8|a[2]).toString(16)).slice(-6);return D.set(e,i),i}function re(e){let s={valid:!1,error:!1,messages:[]};return typeof e=="boolean"?{valid:e,error:!1,messages:[]}:typeof e=="string"?{valid:!1,error:!1,messages:[e]}:(typeof e.valid=="boolean"&&(s.valid=e.valid),typeof e.message=="string"&&(s.messages=[e.message]),typeof e.messages=="string"&&(s.messages=[e.messages]),Array.isArray(e.messages)&&(s.messages=e.messages),e.error===!0&&(s.error=!0),s)}r.formatDateTime=S,r.isColor=X,r.isDate=$,r.isDateInRange=V,r.isEmail=P,r.isFormControl=n,r.isInteger=G,r.isNANPTel=F,r.isNumber=Z,r.isPostalCA=Q,r.isTime=Y,r.isType=l,r.isUrl=K,r.isZip=W,r.momentToFPFormat=g,r.monthToNumber=v,r.normalizeValidationResult=re,r.parseColor=te,r.parseDate=w,r.parseDateToString=x,r.parseInteger=q,r.parseNANPTel=U,r.parseNumber=z,r.parsePostalCA=J,r.parseTime=T,r.parseTimeToString=_,r.parseUrl=j,r.parseZip=B,r.yearToFull=L,Object.defineProperty(r,Symbol.toStringTag,{value:"Module"})})})(f,f.exports);var o=f.exports;class A extends Event{constructor(r){super("validationSuccess",{cancelable:!0});m(this,"submitEvent");this.submitEvent=r}}class N extends Event{constructor(r){super("validationError",{cancelable:!0});m(this,"submitEvent");this.submitEvent=r}}class H{constructor(t,r={}){m(this,"form");m(this,"inputs",[]);m(this,"inputErrors",{});m(this,"messages",{ERROR_MAIN:"There is a problem with your submission.",ERROR_GENERIC:"Enter a valid value.",ERROR_REQUIRED:"This field is required.",OPTION_REQUIRED:"An option must be selected.",CHECKED_REQUIRED:"This must be checked.",ERROR_MAXLENGTH:"This must be ${val} characters or fewer.",ERROR_MINLENGTH:"This must be at least ${val} characters.",ERROR_NUMBER:"This must be a number.",ERROR_INTEGER:"This must be a whole number.",ERROR_TEL:"This is not a valid telephone number.",ERROR_EMAIL:"This is not a valid email address.",ERROR_ZIP:"This is not a valid zip code.",ERROR_POSTAL:"This is not a valid postal code.",ERROR_DATE:"This is not a valid date.",ERROR_DATE_PAST:"The date must be in the past.",ERROR_DATE_FUTURE:"The date must be in the future.",ERROR_DATE_RANGE:"The date is outside the allowed range.",ERROR_TIME:"This is not a valid time.",ERROR_TIME_RANGE:"The time is outside the allowed range.",ERROR_URL:"This is not a valid URL.",ERROR_COLOR:"This is not a valid CSS colour.",ERROR_CUSTOM_VALIDATION:"There was a problem validating this field."});m(this,"debug");m(this,"autoInit");m(this,"preventSubmit",!1);m(this,"hiddenClasses");m(this,"errorMainClasses");m(this,"errorInputClasses");m(this,"dispatchTimeout",0);m(this,"originalNoValidate",!1);m(this,"validationSuccessCallback");m(this,"validationErrorCallback");m(this,"submitHandlerRef",this.submitHandler.bind(this));m(this,"inputInputHandlerRef",this.inputInputHandler.bind(this));m(this,"inputChangeHandlerRef",this.inputChangeHandler.bind(this));m(this,"inputKeydownHandlerRef",this.inputKeydownHandler.bind(this));m(this,"inputHandlers",{number:{parse:o.parseNumber,isValid:o.isNumber,error:this.messages.ERROR_NUMBER},integer:{parse:o.parseInteger,isValid:o.isInteger,error:this.messages.ERROR_INTEGER},tel:{parse:o.parseNANPTel,isValid:o.isNANPTel,error:this.messages.ERROR_TEL},email:{parse:t=>t.trim(),isValid:o.isEmail,error:this.messages.ERROR_EMAIL},zip:{parse:o.parseZip,isValid:o.isZip,error:this.messages.ERROR_ZIP},postal:{parse:o.parsePostalCA,isValid:o.isPostalCA,error:this.messages.ERROR_POSTAL},url:{parse:o.parseUrl,isValid:o.isUrl,error:this.messages.ERROR_URL},date:{parse:o.parseDateToString,isValid:o.isDate,error:this.messages.ERROR_DATE},time:{parse:o.parseTimeToString,isValid:o.isTime,error:this.messages.ERROR_TIME},color:{parse:t=>t.trim().toLowerCase(),isValid:o.isColor,error:this.messages.ERROR_COLOR}});m(this,"isSubmitting",!1);if(!t)throw new Error("Validator requires a form to be passed as the first argument.");if(!(t instanceof HTMLFormElement))throw new Error("form argument must be an instance of HTMLFormElement");this.form=t,(t.dataset.preventSubmit===""||t.dataset.preventSubmit)&&(this.preventSubmit=!0),Object.assign(this.messages,r.messages||{}),this.debug=r.debug||!1,this.autoInit=r.autoInit!==!1,this.preventSubmit=r.preventSubmit!==void 0?r.preventSubmit:this.preventSubmit,this.hiddenClasses=r.hiddenClasses||"hidden opacity-0",this.errorMainClasses=r.errorMainClasses||"m-2 border border-red-500 bg-red-100 p-3 dark:bg-red-900/80 text-center",this.errorInputClasses=r.errorInputClasses||"border-red-600 dark:border-red-500",this.validationSuccessCallback=r.validationSuccessCallback||(()=>{}),this.validationErrorCallback=r.validationErrorCallback||(()=>{}),this.autoInit&&this.init(),new MutationObserver(()=>this.autoInit&&this.init()).observe(t,{childList:!0})}addEventListeners(){this.form.addEventListener("submit",this.submitHandlerRef),this.form.addEventListener("input",this.inputInputHandlerRef),this.form.addEventListener("change",this.inputChangeHandlerRef),this.form.addEventListener("keydown",this.inputKeydownHandlerRef),this.form.addEventListener("remove",this.destroy,{once:!0})}removeEventListeners(){this.form.removeEventListener("submit",this.submitHandlerRef),this.form.removeEventListener("input",this.inputInputHandlerRef),this.form.removeEventListener("change",this.inputChangeHandlerRef),this.form.removeEventListener("keydown",this.inputKeydownHandlerRef),this.form.removeEventListener("remove",this.destroy)}init(){this.inputs=Array.from(this.form.elements),this.inputs.forEach(t=>{!t.name&&!t.id&&(t.id=`vl-input-${Math.random().toString(36).slice(2)}`),this.inputErrors[t.name||t.id]=[]}),this.originalNoValidate=this.form.hasAttribute("novalidate"),this.form.setAttribute("novalidate","novalidate"),this.removeEventListeners(),this.addEventListeners()}getErrorEl(t){const r=document.getElementById(t.name+"-error");if(r)return r;const n=document.getElementById(t.id+"-error");if(n)return n;const l=t.getAttribute("aria-describedby");return l?document.getElementById(l):null}addErrorMain(t){const r=document.createElement("div");r.id="form-error-main",this.errorMainClasses.split(" ").forEach(n=>{r.classList.add(n)}),t?r.innerHTML=t:r.innerHTML=this.messages.ERROR_MAIN,this.form.appendChild(r)}addInputError(t,r=t.dataset.errorDefault||this.messages.ERROR_GENERIC){const n=t.name||t.id;this.debug&&console.log("Invalid value for "+n+": "+r),n in this.inputErrors||(this.inputErrors[n]=[]),this.inputErrors[n].includes(r)||this.inputErrors[n].push(r)}showInputErrors(t){if(!t||!t.name&&!t.id)return;const r=t.name||t.id,n=r in this.inputErrors?this.inputErrors[r]:[];if(!n.length)return;t.setAttribute("aria-invalid","true"),this.errorInputClasses.split(" ").forEach(g=>{t.classList.add(g)});let l=this.getErrorEl(t);l&&(l.innerHTML=n.join("<br>"),this.hiddenClasses.split(" ").forEach(g=>{l&&l.classList.remove(g)}))}showFormErrors(){if(this.inputs.forEach(t=>this.showInputErrors(t)),Object.values(this.inputErrors).some(t=>Array.isArray(t)&&t.length)){const t=this.form.querySelectorAll("#form-error-main");t.length?t.forEach(r=>{r.innerHTML||(r.innerHTML=this.messages.ERROR_MAIN),this.hiddenClasses.split(" ").forEach(n=>{r.classList.remove(n)})}):this.addErrorMain()}}clearInputErrors(t){this.inputErrors[t.name||t.id]=[],t.removeAttribute("aria-invalid");let r=this.getErrorEl(t);r&&(this.errorInputClasses.split(" ").forEach(n=>{t.classList.remove(n)}),this.hiddenClasses.split(" ").forEach(n=>{r&&r.classList.add(n)}),r.textContent="")}clearFormErrors(){this.form.querySelectorAll("#form-error-main").forEach(t=>{this.hiddenClasses.split(" ").forEach(r=>{t.classList.add(r)})}),this.inputs.forEach(t=>this.clearInputErrors(t))}validateRequired(t){let r=!0;if(t.required&&(t.value===""||t instanceof HTMLInputElement&&["checkbox","radio"].includes(t.type)&&!t.checked))if(t instanceof HTMLInputElement&&["checkbox","radio"].includes(t.type)){let n=!1,l=t.name;const g=this.form.querySelectorAll(`input[name="${l}"]`);if(g.forEach(v=>{if(v instanceof HTMLInputElement&&v.checked===!0){n=!0;return}}),n===!1){r=!1;let v=g.length>1?this.messages.OPTION_REQUIRED:this.messages.CHECKED_REQUIRED;t.dataset.errorDefault&&(v=t.dataset.errorDefault),this.addInputError(t,v)}}else o.isFormControl(t)&&(r=!1,this.addInputError(t,t.dataset.errorDefault||this.messages.ERROR_REQUIRED));return r}validateLength(t){let r=!0;if(t.disabled)return r;if((t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&t.value.length){let n=t.minLength>0?t.minLength:t.dataset.minLength?parseInt(t.dataset.minLength):0,l=t.maxLength>0&&t.maxLength<5e5?t.maxLength:t.dataset.maxLength?parseInt(t.dataset.maxLength):1/0;n>0&&t.value.length<n&&(r=!1,this.addInputError(t,this.messages.ERROR_MINLENGTH.replace("${val}",n.toString()))),t.value.length>l&&(r=!1,this.addInputError(t,this.messages.ERROR_MAXLENGTH.replace("${val}",l.toString())))}return r}validateInputType(t){const r=t.dataset.type||t.type,n=this.inputHandlers[t.type]||this.inputHandlers[r];if(n){const l=t.dataset.dateFormat||t.dataset.timeFormat,g=n.parse(t.value,l),v=["date","time","datetime-local","month","week"];if(g.length&&!v.includes(t.type)&&(t.value=g),!n.isValid(t.value))return this.addInputError(t,n.error),!1}return!0}validateDateRange(t){if(t.dataset.dateRange){const r=t.dataset.dateRange,n=o.parseDate(t.value);if(!isNaN(n.getTime())&&!o.isDateInRange(n,r)){let l=t.dataset.errorDefault||this.messages.ERROR_DATE_RANGE;return r==="past"?l=this.messages.ERROR_DATE_PAST:r==="future"&&(l=this.messages.ERROR_DATE_FUTURE),this.addInputError(t,l),!1}}return!0}validatePattern(t){const r=t.dataset.pattern||t instanceof HTMLInputElement&&t.pattern||null;return r&&!new RegExp(r).test(t.value)?(this.addInputError(t),!1):!0}async validateCustom(t){if(t.disabled)return!0;const r=t.dataset.validation;if(!r||typeof r!="string")return!0;const n=window[r];if(!n||typeof n!="function")return!0;let l;try{l=await Promise.resolve(n(t.value)),l=o.normalizeValidationResult(l)}catch{return this.addInputError(t,this.messages.ERROR_CUSTOM_VALIDATION),!1}const g=l.messages.join("<br>")||this.messages.ERROR_CUSTOM_VALIDATION;return l.valid||this.addInputError(t,g),l.valid}async validateInput(t){if(!(t instanceof HTMLInputElement)||!t.value.length)return!0;let r=!0;return t.disabled||(r=this.validateInputType(t)&&r,r=this.validateDateRange(t)&&r,r=this.validatePattern(t)&&r,r=await this.validateCustom(t)&&r),r}async validate(t){let r=!0;for(const n of this.inputs)n.disabled||(r=this.validateRequired(n)&&r,r=this.validateLength(n)&&r,r=await this.validateInput(n)&&r,n.value.length||(r=await this.validateCustom(n)&&r));return r}async submitHandler(t){if(this.isSubmitting)return;t.preventDefault(),this.clearFormErrors();let r=await this.validate(t);this.showFormErrors();const n=new A(t),l=new N(t);r?(this.form.dispatchEvent(n),this.validationSuccessCallback&&this.validationSuccessCallback(t)):(this.form.dispatchEvent(l),this.validationErrorCallback&&this.validationErrorCallback(t)),r&&!this.preventSubmit&&(this.isSubmitting=!0,n.defaultPrevented||this.form.submit(),this.isSubmitting=!1)}shouldSkipValidation(t){return typeof t.dataset.novalidate>"u"?!1:t.dataset.novalidate===""?!0:t.dataset.novalidate==="true"}async inputChangeHandler(t){!(t.target instanceof HTMLInputElement)||this.shouldSkipValidation(t.target)||(this.clearInputErrors(t.target),this.validateLength(t.target),await this.validateInput(t.target),this.showInputErrors(t.target))}inputInputHandler(t){const r=t.target;this.shouldSkipValidation(r)||(o.isType(r,"integer")&&(r.value=o.parseInteger(r.value)),r.type!=="number"&&o.isType(r,["number","float","decimal"])&&(r.value=o.parseNumber(r.value)),o.isType(r,"color")&&this.syncColorInput(t))}syncColorInput(t){let r=t.target,n=r;r.type==="color"&&(n=this.form.querySelector(`#${r.id.replace(/-color/,"")}`));let l=this.form.querySelector(`#${n.id}-color-label`);if((r.dataset.type||"")==="color"){let g=this.form.querySelector(`input#${r.id}-color`);if(!g||!o.isColor(r.value))return;g.value=o.parseColor(r.value)}r.type==="color"&&(n.value=r.value),l&&(l.style.backgroundColor=r.value),clearTimeout(this.dispatchTimeout),this.dispatchTimeout=window.setTimeout(()=>{n.dispatchEvent(new Event("change",{bubbles:!0}))},200)}inputKeydownHandler(t){t.target instanceof HTMLInputElement&&o.isType(t.target,"integer")&&(t.key==="ArrowUp"?(t.preventDefault(),t.target.value===""&&(t.target.value="0"),t.target.value=(parseInt(t.target.value)+1).toString()):t.key==="ArrowDown"&&(parseInt(t.target.value)>0?t.target.value=(parseInt(t.target.value)-1).toString():t.target.value="0"))}destroy(){this.removeEventListeners(),this.originalNoValidate||this.form.removeAttribute("novalidate")}}return H});
1
+ (function(v,E){typeof exports=="object"&&typeof module<"u"?module.exports=E():typeof define=="function"&&define.amd?define(E):(v=typeof globalThis<"u"?globalThis:v||self,v.Validator=E())})(this,function(){"use strict";var ae=Object.defineProperty;var se=(v,E,o)=>E in v?ae(v,E,{enumerable:!0,configurable:!0,writable:!0,value:o}):v[E]=o;var m=(v,E,o)=>(se(v,typeof E!="symbol"?E+"":E,o),o);var v=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},E={exports:{}};(function(M,t){(function(r,n){n(t)})(v,function(r){function n(e){return e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement}function l(e,s){typeof s=="string"&&(s=[s]);const a=e.dataset.type||"",i=e.type;return!!(s.includes(a)||s.includes(i))}function g(e){return e.replace(/YYYY/g,"Y").replace(/YY/g,"y").replace(/MMMM/g,"F").replace(/MMM/g,"{3}").replace(/MM/g,"{2}").replace(/M/g,"n").replace(/DD/g,"{5}").replace(/D/g,"j").replace(/dddd/g,"l").replace(/ddd/g,"D").replace(/dd/g,"D").replace(/d/g,"w").replace(/HH/g,"{6}").replace(/H/g,"G").replace(/hh/g,"h").replace(/mm/g,"i").replace(/m/g,"i").replace(/ss/g,"S").replace(/s/g,"s").replace(/A/gi,"K").replace(/\{3\}/g,"M").replace(/\{2\}/g,"m").replace(/\{5\}/g,"d").replace(/\{6\}/g,"H")}function f(e){const s=parseInt(e);if(typeof e=="number"||!isNaN(s))return s-1;const a=new Date(`1 ${e} 2000`).getMonth();if(!isNaN(a))return a;const i={ja:0,en:0,fe:1,fé:1,ap:3,ab:3,av:3,mai:4,juin:5,juil:6,au:7,ag:7,ao:7,se:8,o:9,n:10,d:11};for(const h in i)if(e.toLowerCase().startsWith(h))return i[h];throw new Error("Invalid month name: "+e)}function L(e){return typeof e=="string"&&(e=parseInt(e.replace(/\D/g,""))),e>99?e:e<(new Date().getFullYear()+20)%100?e+2e3:e+1900}function w(e){if(e instanceof Date)return e;e=e.trim().toLowerCase();let s=0,a=0,i=0,h=0,d=0,u=0;const p=new RegExp(/\d{1,2}\:\d\d(?:\:\d\ds?)?\s?(?:[a|p]m?)?/gi);if(p.test(e)){const R=e.match(p)[0];e=e.replace(R,"").trim();const y=T(R);if(y!==null&&({hour:h,minute:d,second:u}=y),e.length<=2){const C=new Date;return new Date(C.getFullYear(),C.getMonth(),C.getDate(),h,d,u)}}const b=/(^|\b)(mo|tu|we|th|fr|sa|su|lu|mard|mer|jeu|ve|dom)[\w]*\.?/gi;e=e.replace(b,"").trim();const c=new Date(new Date().setHours(0,0,0,0));if(/(now|today)/.test(e))return c;if(e.includes("tomorrow"))return new Date(c.setDate(c.getDate()+1));e.length===8&&(e=e.replace(/(\d\d\d\d)(\d\d)(\d\d)/,"$1-$2-$3")),e.length===6&&(e=e.replace(/(\d\d)(\d\d)(\d\d)/,L(e.slice(0,2))+"-$2-$3"));try{({year:s,month:a,day:i}=O(e))}catch{return new Date("")}return new Date(s,a-1,i,h,d,u)}function k(e,s=[null,null,null]){const a=i=>i.filter(h=>!s.includes(h));return e===0||e>31?a(["y"]):e>12?a(["d","y"]):e>=1&&e<=12?a(["m","d","y"]):[]}function O(e){const s=e.split(/[\s-/:.,]+/).filter(d=>d!=="");if(s.length<3){if(e.match(/\d{4}/)!==null)throw new Error("Invalid Date");s.unshift(String(new Date().getFullYear()))}const a={year:0,month:0,day:0};function i(d,u){d==="year"?a.year=L(u):a[d]=u}let h=0;for(;!(a.year&&a.month&&a.day);){e:for(const d of s){if(h++,/^[a-zA-Zé]+$/.test(d)){a.month||i("month",f(d)+1);continue}if(/^'\d\d$/.test(d)||/^\d{3,5}$/.test(d)){a.year||i("year",parseInt(d.replace(/'/,"")));continue}const u=parseInt(d);if(isNaN(u))throw console.error(`not date because ${d} isNaN`),new Error("Invalid Date");const p=k(u,[a.year?"y":null,a.month?"m":null,a.day?"d":null]);if(p.length==1){if(p[0]==="m"&&!a.month){i("month",u);continue e}if(p[0]==="d"&&!a.day){i("day",u);continue e}if(p[0]==="y"&&!a.year){i("year",u);continue e}}h>3&&(!a.month&&p.includes("m")?i("month",u):!a.day&&p.includes("d")&&i("day",u))}if(h>6)throw new Error("Invalid Date")}if(a.year&&a.month&&a.day)return a;throw new Error("Invalid Date")}function T(e){if(e=e.trim().toLowerCase(),e==="now"){const c=new Date;return{hour:c.getHours(),minute:c.getMinutes(),second:c.getSeconds()}}const s=e.match(/(\d{3,4})/);if(s){const c=s[1].length,R=s[1].slice(0,c==3?1:2),y=s[1].slice(-2);e=e.replace(s[1],R+":"+y)}const a=new RegExp(/^(\d{1,2})(?::(\d{1,2}))?\s*(?:(a|p)m?)?$/i);if(a.test(e)){const c=e.match(a);if(c===null)return null;e=c[1]+":"+(c[2]||"00")+(c[3]||"")}const i=new RegExp(/^(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?\s*(?:(a|p)m?)?$/i);if(!i.test(e))return null;const h=e.match(i);if(h===null)return null;const d=parseInt(h[1]),u=parseInt(h[2]),p=h[3]?parseInt(h[3]):0,b=h[4];return isNaN(d)||isNaN(u)||isNaN(p)?null:b==="p"&&d<12?{hour:d+12,minute:u,second:p}:b==="a"&&d===12?{hour:0,minute:u,second:p}:d<0||d>23||u<0||u>59||p<0||p>59?null:{hour:d,minute:u,second:p}}function _(e,s="h:mm A"){const a=T(e);if(a){const i=new Date;return i.setHours(a.hour),i.setMinutes(a.minute),i.setSeconds(a.second),i.setMilliseconds(0),S(i,s)}return""}function S(e,s="YYYY-MM-DD"){if(e=w(e),isNaN(e.getTime()))return"";const a={y:e.getFullYear(),M:e.getMonth(),D:e.getDate(),W:e.getDay(),H:e.getHours(),m:e.getMinutes(),s:e.getSeconds(),ms:e.getMilliseconds()},i=(c,R=2)=>(c+"").padStart(R,"0"),h=()=>a.H%12||12,d=c=>c<12?"AM":"PM",u=c=>"January|February|March|April|May|June|July|August|September|October|November|December".split("|")[c];function p(c,R=0){const y="Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday".split("|");return R?y[c].slice(0,R):y[c]}const b={YY:String(a.y).slice(-2),YYYY:a.y,M:a.M+1,MM:i(a.M+1),MMMM:u(a.M),MMM:u(a.M).slice(0,3),D:String(a.D),DD:i(a.D),d:String(a.W),dd:p(a.W,2),ddd:p(a.W,3),dddd:p(a.W),H:String(a.H),HH:i(a.H),h:h(),hh:i(h()),A:d(a.H),a:d(a.H).toLowerCase(),m:String(a.m),mm:i(a.m),s:String(a.s),ss:i(a.s),SSS:i(a.ms,3)};return s.replace(/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,(c,R)=>R||b[c])}function x(e,s){const a=w(e);return isNaN(a.getTime())?"":((!s||s.length===0)&&(s="YYYY-MMM-DD"),S(a,s))}function $(e){if(typeof e!="string"&&!(e instanceof Date))return!1;let s=w(e);return s==null?!1:!isNaN(s.getTime())}function V(e,s){return!(s==="past"&&e>new Date||s==="future"&&e.getTime()<new Date().setHours(0,0,0,0))}function Y(e){let s=T(e);return s===null?!1:!isNaN(s.hour)&&!isNaN(s.minute)&&!isNaN(s.second)}function P(e){if(e.length>255||!new RegExp(/^.+@.+\.[a-zA-Z0-9]{2,}$/).test(e))return!1;let s="";return s+="^([a-zA-Z0-9!#$%'*+/=?^_`{|}~-]+",s+="(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*",s+="|",s+='"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*"',s+=")@(",s+="(",s+="(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+",s+="[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?",s+=")",s+=")$",new RegExp(s).test(e)}function U(e){return e=e.replace(/^[^2-90]+/g,""),e=e.replace(/(\d\d\d).*?(\d\d\d).*?(\d\d\d\d)(.*)/,"$1-$2-$3$4"),e}function F(e){return/^\d\d\d-\d\d\d-\d\d\d\d$/.test(e)}function q(e){return e.replace(/[^0-9]/g,"")}function Z(e){return/^\-?\d*\.?\d*$/.test(e)}function z(e){return e.replace(/[^\-0-9.]/g,"").replace(/(^-)|(-)/g,(s,a)=>a?"-":"").replace(/(\..*)\./g,"$1")}function G(e){return/^\-?\d*$/.test(e)}function j(e){return e=e.trim(),new RegExp("^(?:[a-z+]+:)?//","i").test(e)?e:"https://"+e}function B(e){return new RegExp("^(?:[-a-z+]+:)?//","i").test(e)}function K(e){return e=e.replace(/[^0-9]/g,"").replace(/(.{5})(.*)/,"$1-$2").trim(),e.length===6&&(e=e.replace(/-/,"")),e}function W(e){return new RegExp(/^\d{5}(-\d{4})?$/).test(e)}function J(e){return e=e.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/(.{3})\s*(.*)/,"$1 $2").trim(),e}function Q(e){return new RegExp(/^[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ] ?[0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]$/).test(e)}function X(e){return["transparent","currentColor"].includes(e)?!0:typeof e!="string"||!e.trim()?!1:typeof CSS=="object"&&typeof CSS.supports=="function"?CSS.supports("color",e):ee(e)}function ee(e){const s=new RegExp(/^rgba?\(\s*(\d{1,3}%?,\s*){2}\d{1,3}%?\s*(?:,\s*(\.\d+|0+(\.\d+)?|1(\.0+)?|0|1\.0|\d{1,2}(\.\d*)?%|100%))?\s*\)$/),a=new RegExp(/^hsla?\(\s*\d+(deg|grad|rad|turn)?,\s*\d{1,3}%,\s*\s*\d{1,3}%(?:,\s*(\.\d+|0+(\.\d+)?|1(\.0+)?|0|1\.0|\d{1,2}(\.\d*)?%|100%))?\s*\)$/),i=new RegExp(/^rgba?\(\s*(\d{1,3}%?\s+){2}\d{1,3}%?\s*(?:\s*\/\s*(\.\d+|0+(\.\d+)?|1(\.0+)?|0|1\.0|\d{1,2}(\.\d*)?%|100%))?\s*\)$/),h=new RegExp(/^hsla?\(\s*\d+(deg|grad|rad|turn)?\s+\d{1,3}%\s+\s*\d{1,3}%(?:\s*\/\s*(\.\d+|0+(\.\d+)?|1(\.0+)?|0|1\.0|\d{1,2}(\.\d*)?%|100%))?\s*\)$/),d=new RegExp(/^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);let u="aliceblue|antiquewhite|aqua|aquamarine|azure|beige|bisque|black|blanchedalmond|blue|blueviolet|brown|burlywood|cadetblue|chartreuse|chocolate|coral|cornflowerblue|cornsilk|crimson|cyan|darkblue|darkcyan|darkgoldenrod|darkgray|darkgreen|darkgrey|darkkhaki|darkmagenta|darkolivegreen|darkorange|darkorchid|darkred|darksalmon|darkseagreen|darkslateblue|darkslategray|darkslategrey|darkturquoise|darkviolet|deeppink|deepskyblue|dimgray|dimgrey|dodgerblue|firebrick|floralwhite|forestgreen|fuchsia|gainsboro|ghostwhite|gold|goldenrod|gray|green|greenyellow|grey|honeydew|hotpink|indianred|indigo|ivory|khaki|lavender|lavenderblush|lawngreen|lemonchiffon|lightblue|lightcoral|lightcyan|lightgoldenrodyellow|lightgray|lightgreen|lightgrey|lightpink|lightsalmon|lightseagreen|lightskyblue|lightslategray|lightslategrey|lightsteelblue|lightyellow|lime|limegreen|linen|magenta|maroon|mediumaquamarine|mediumblue|mediumorchid|mediumpurple|mediumseagreen|mediumslateblue|mediumspringgreen|mediumturquoise|mediumvioletred|midnightblue|mintcream|mistyrose|moccasin|navajowhite|navy|oldlace|olive|olivedrab|orange|orangered|orchid|palegoldenrod|palegreen|paleturquoise|palevioletred|papayawhip|peachpuff|peru|pink|plum|powderblue|purple|rebeccapurple|red|rosybrown|royalblue|saddlebrown|salmon|sandybrown|seagreen|seashell|sienna|silver|skyblue|slateblue|slategray|slategrey|snow|springgreen|steelblue|tan|teal|thistle|tomato|turquoise|violet|wheat|white|whitesmoke|yellow|yellowgreen";const p=new RegExp(`^(${u})$`,"i");return s.test(e)||a.test(e)||i.test(e)||h.test(e)||d.test(e)||p.test(e)}let I=null;const D=new Map;function te(e){if(e=e.trim().toLowerCase(),["transparent","currentcolor"].includes(e))return e;if(D.has(e))return D.get(e);I===null&&(I=document.createElement("canvas"),I.willReadFrequently=!0);let s=I.getContext("2d");if(!s)throw new Error("Can't get context from colorCanvas");s.fillStyle=e,s.fillRect(0,0,1,1);let a=s.getImageData(0,0,1,1).data,i="#"+("000000"+(a[0]<<16|a[1]<<8|a[2]).toString(16)).slice(-6);return D.set(e,i),i}function re(e){let s={valid:!1,error:!1,messages:[]};return typeof e=="boolean"?{valid:e,error:!1,messages:[]}:typeof e=="string"?{valid:!1,error:!1,messages:[e]}:(typeof e.valid=="boolean"&&(s.valid=e.valid),typeof e.message=="string"&&(s.messages=[e.message]),typeof e.messages=="string"&&(s.messages=[e.messages]),Array.isArray(e.messages)&&(s.messages=e.messages),e.error===!0&&(s.error=!0),s)}r.formatDateTime=S,r.isColor=X,r.isDate=$,r.isDateInRange=V,r.isEmail=P,r.isFormControl=n,r.isInteger=G,r.isNANPTel=F,r.isNumber=Z,r.isPostalCA=Q,r.isTime=Y,r.isType=l,r.isUrl=B,r.isZip=W,r.momentToFPFormat=g,r.monthToNumber=f,r.normalizeValidationResult=re,r.parseColor=te,r.parseDate=w,r.parseDateToString=x,r.parseInteger=q,r.parseNANPTel=U,r.parseNumber=z,r.parsePostalCA=J,r.parseTime=T,r.parseTimeToString=_,r.parseUrl=j,r.parseZip=K,r.yearToFull=L,Object.defineProperty(r,Symbol.toStringTag,{value:"Module"})})})(E,E.exports);var o=E.exports;class A extends Event{constructor(r){super("validationSuccess",{cancelable:!0});m(this,"submitEvent");this.submitEvent=r}}class N extends Event{constructor(r){super("validationError",{cancelable:!0});m(this,"submitEvent");this.submitEvent=r}}class H{constructor(t,r={}){m(this,"form");m(this,"inputs",[]);m(this,"inputErrors",{});m(this,"messages",{ERROR_MAIN:"There is a problem with your submission.",ERROR_GENERIC:"Enter a valid value.",ERROR_REQUIRED:"This field is required.",OPTION_REQUIRED:"An option must be selected.",CHECKED_REQUIRED:"This must be checked.",ERROR_MAXLENGTH:"This must be ${val} characters or fewer.",ERROR_MINLENGTH:"This must be at least ${val} characters.",ERROR_NUMBER:"This must be a number.",ERROR_INTEGER:"This must be a whole number.",ERROR_TEL:"This is not a valid telephone number.",ERROR_EMAIL:"This is not a valid email address.",ERROR_ZIP:"This is not a valid zip code.",ERROR_POSTAL:"This is not a valid postal code.",ERROR_DATE:"This is not a valid date.",ERROR_DATE_PAST:"The date must be in the past.",ERROR_DATE_FUTURE:"The date must be in the future.",ERROR_DATE_RANGE:"The date is outside the allowed range.",ERROR_TIME:"This is not a valid time.",ERROR_TIME_RANGE:"The time is outside the allowed range.",ERROR_URL:"This is not a valid URL.",ERROR_COLOR:"This is not a valid CSS colour.",ERROR_CUSTOM_VALIDATION:"There was a problem validating this field."});m(this,"debug");m(this,"autoInit");m(this,"preventSubmit",!1);m(this,"hiddenClasses");m(this,"errorMainClasses");m(this,"errorInputClasses");m(this,"dispatchTimeout",0);m(this,"originalNoValidate",!1);m(this,"validationSuccessCallback");m(this,"validationErrorCallback");m(this,"submitHandlerRef",this.submitHandler.bind(this));m(this,"inputInputHandlerRef",this.inputInputHandler.bind(this));m(this,"inputChangeHandlerRef",this.inputChangeHandler.bind(this));m(this,"inputKeydownHandlerRef",this.inputKeydownHandler.bind(this));m(this,"inputHandlers",{number:{parse:o.parseNumber,isValid:o.isNumber,error:this.messages.ERROR_NUMBER},integer:{parse:o.parseInteger,isValid:o.isInteger,error:this.messages.ERROR_INTEGER},tel:{parse:o.parseNANPTel,isValid:o.isNANPTel,error:this.messages.ERROR_TEL},email:{parse:t=>t.trim(),isValid:o.isEmail,error:this.messages.ERROR_EMAIL},zip:{parse:o.parseZip,isValid:o.isZip,error:this.messages.ERROR_ZIP},postal:{parse:o.parsePostalCA,isValid:o.isPostalCA,error:this.messages.ERROR_POSTAL},url:{parse:o.parseUrl,isValid:o.isUrl,error:this.messages.ERROR_URL},date:{parse:o.parseDateToString,isValid:o.isDate,error:this.messages.ERROR_DATE},time:{parse:o.parseTimeToString,isValid:o.isTime,error:this.messages.ERROR_TIME},color:{parse:t=>t.trim().toLowerCase(),isValid:o.isColor,error:this.messages.ERROR_COLOR}});m(this,"isSubmitting",!1);if(!t)throw new Error("Validator requires a form to be passed as the first argument.");if(!(t instanceof HTMLFormElement))throw new Error("form argument must be an instance of HTMLFormElement");this.form=t,(t.dataset.preventSubmit===""||t.dataset.preventSubmit)&&(this.preventSubmit=!0),Object.assign(this.messages,r.messages||{}),this.debug=r.debug||!1,this.autoInit=r.autoInit!==!1,this.preventSubmit=r.preventSubmit!==void 0?r.preventSubmit:this.preventSubmit,this.hiddenClasses=r.hiddenClasses||"hidden opacity-0",this.errorMainClasses=r.errorMainClasses||"m-2 border border-red-500 bg-red-100 p-3 dark:bg-red-900/80 text-center",this.errorInputClasses=r.errorInputClasses||"border-red-600 dark:border-red-500",this.validationSuccessCallback=r.validationSuccessCallback||(()=>{}),this.validationErrorCallback=r.validationErrorCallback||(()=>{}),this.autoInit&&this.init(),new MutationObserver(()=>this.autoInit&&this.init()).observe(t,{childList:!0})}addEventListeners(){this.form.addEventListener("submit",this.submitHandlerRef),this.form.addEventListener("input",this.inputInputHandlerRef),this.form.addEventListener("change",this.inputChangeHandlerRef),this.form.addEventListener("keydown",this.inputKeydownHandlerRef),this.form.addEventListener("remove",this.destroy,{once:!0})}removeEventListeners(){this.form.removeEventListener("submit",this.submitHandlerRef),this.form.removeEventListener("input",this.inputInputHandlerRef),this.form.removeEventListener("change",this.inputChangeHandlerRef),this.form.removeEventListener("keydown",this.inputKeydownHandlerRef),this.form.removeEventListener("remove",this.destroy)}init(){this.inputs=Array.from(this.form.elements),this.inputs.forEach(t=>{!t.name&&!t.id&&(t.id=`vl-input-${Math.random().toString(36).slice(2)}`),this.inputErrors[t.name||t.id]=[]}),this.originalNoValidate=this.form.hasAttribute("novalidate"),this.form.setAttribute("novalidate","novalidate"),this.removeEventListeners(),this.addEventListeners()}getErrorEl(t){const r=f=>this.form.querySelector(`#${f}`)||document.getElementById(f)||null,n=t.getAttribute("aria-describedby");if(n){const f=r(n);if(f)return f}const l=r(t.id+"-error");return l||r(t.name+"-error")||null}addErrorMain(t){const r=document.createElement("div");r.id="form-error-main",this.errorMainClasses.split(" ").forEach(n=>{r.classList.add(n)}),t?r.innerHTML=t:r.innerHTML=this.messages.ERROR_MAIN,this.form.appendChild(r)}addInputError(t,r=t.dataset.errorDefault||this.messages.ERROR_GENERIC){const n=t.name||t.id;this.debug&&console.log("Invalid value for "+n+": "+r),n in this.inputErrors||(this.inputErrors[n]=[]),this.inputErrors[n].includes(r)||this.inputErrors[n].push(r)}showInputErrors(t){if(!t||!t.name&&!t.id)return;const r=t.name||t.id,n=r in this.inputErrors?this.inputErrors[r]:[];if(!n.length)return;t.setAttribute("aria-invalid","true"),this.errorInputClasses.split(" ").forEach(g=>{t.classList.add(g)});let l=this.getErrorEl(t);l&&(l.innerHTML=n.join("<br>"),this.hiddenClasses.split(" ").forEach(g=>{l&&l.classList.remove(g)}))}showFormErrors(){if(this.inputs.forEach(t=>this.showInputErrors(t)),Object.values(this.inputErrors).some(t=>Array.isArray(t)&&t.length)){const t=this.form.querySelectorAll("#form-error-main");t.length?t.forEach(r=>{r.innerHTML||(r.innerHTML=this.messages.ERROR_MAIN),this.hiddenClasses.split(" ").forEach(n=>{r.classList.remove(n)})}):this.addErrorMain()}}clearInputErrors(t){this.inputErrors[t.name||t.id]=[],t.removeAttribute("aria-invalid");let r=this.getErrorEl(t);r&&(this.errorInputClasses.split(" ").forEach(n=>{t.classList.remove(n)}),this.hiddenClasses.split(" ").forEach(n=>{r&&r.classList.add(n)}),r.textContent="")}clearFormErrors(){this.form.querySelectorAll("#form-error-main").forEach(t=>{this.hiddenClasses.split(" ").forEach(r=>{t.classList.add(r)})}),this.inputs.forEach(t=>this.clearInputErrors(t))}validateRequired(t){let r=!0;if(t.required&&(t.value===""||t instanceof HTMLInputElement&&["checkbox","radio"].includes(t.type)&&!t.checked))if(t instanceof HTMLInputElement&&["checkbox","radio"].includes(t.type)){let n=!1,l=t.name;const g=this.form.querySelectorAll(`input[name="${l}"]`);if(g.forEach(f=>{if(f instanceof HTMLInputElement&&f.checked===!0){n=!0;return}}),n===!1){r=!1;let f=g.length>1?this.messages.OPTION_REQUIRED:this.messages.CHECKED_REQUIRED;t.dataset.errorDefault&&(f=t.dataset.errorDefault),this.addInputError(t,f)}}else o.isFormControl(t)&&(r=!1,this.addInputError(t,t.dataset.errorDefault||this.messages.ERROR_REQUIRED));return r}validateLength(t){let r=!0;if(t.disabled)return r;if((t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&t.value.length){let n=t.minLength>0?t.minLength:t.dataset.minLength?parseInt(t.dataset.minLength):0,l=t.maxLength>0&&t.maxLength<5e5?t.maxLength:t.dataset.maxLength?parseInt(t.dataset.maxLength):1/0;n>0&&t.value.length<n&&(r=!1,this.addInputError(t,this.messages.ERROR_MINLENGTH.replace("${val}",n.toString()))),t.value.length>l&&(r=!1,this.addInputError(t,this.messages.ERROR_MAXLENGTH.replace("${val}",l.toString())))}return r}validateInputType(t){const r=t.dataset.type||t.type,n=this.inputHandlers[t.type]||this.inputHandlers[r];if(n){const l=t.dataset.dateFormat||t.dataset.timeFormat,g=n.parse(t.value,l),f=["date","time","datetime-local","month","week"];if(g.length&&!f.includes(t.type)&&(t.value=g),!n.isValid(t.value))return this.addInputError(t,n.error),!1}return!0}validateDateRange(t){if(t.dataset.dateRange){const r=t.dataset.dateRange,n=o.parseDate(t.value);if(!isNaN(n.getTime())&&!o.isDateInRange(n,r)){let l=t.dataset.errorDefault||this.messages.ERROR_DATE_RANGE;return r==="past"?l=this.messages.ERROR_DATE_PAST:r==="future"&&(l=this.messages.ERROR_DATE_FUTURE),this.addInputError(t,l),!1}}return!0}validatePattern(t){const r=t.dataset.pattern||t instanceof HTMLInputElement&&t.pattern||null;return r&&!new RegExp(r).test(t.value)?(this.addInputError(t),!1):!0}async validateCustom(t){if(t.disabled)return!0;const r=t.dataset.validation;if(!r||typeof r!="string")return!0;const n=window[r];if(!n||typeof n!="function")return!0;let l;try{l=await Promise.resolve(n(t.value)),l=o.normalizeValidationResult(l)}catch{return this.addInputError(t,this.messages.ERROR_CUSTOM_VALIDATION),!1}const g=l.messages.join("<br>")||this.messages.ERROR_CUSTOM_VALIDATION;return l.valid||this.addInputError(t,g),l.valid}async validateInput(t){if(!(t instanceof HTMLInputElement)||!t.value.length)return!0;let r=!0;return t.disabled||(r=this.validateInputType(t)&&r,r=this.validateDateRange(t)&&r,r=this.validatePattern(t)&&r,r=await this.validateCustom(t)&&r),r}async validate(t){let r=!0;for(const n of this.inputs)n.disabled||(r=this.validateRequired(n)&&r,r=this.validateLength(n)&&r,r=await this.validateInput(n)&&r,n.value.length||(r=await this.validateCustom(n)&&r));return r}async submitHandler(t){if(this.isSubmitting)return;t.preventDefault(),this.clearFormErrors();let r=await this.validate(t);this.showFormErrors();const n=new A(t),l=new N(t);r?(this.form.dispatchEvent(n),this.validationSuccessCallback&&this.validationSuccessCallback(t)):(this.form.dispatchEvent(l),this.validationErrorCallback&&this.validationErrorCallback(t)),r&&!this.preventSubmit&&(this.isSubmitting=!0,n.defaultPrevented||this.form.submit(),this.isSubmitting=!1)}shouldSkipValidation(t){return typeof t.dataset.novalidate>"u"?!1:t.dataset.novalidate===""?!0:t.dataset.novalidate==="true"}async inputChangeHandler(t){!(t.target instanceof HTMLInputElement)||this.shouldSkipValidation(t.target)||(this.clearInputErrors(t.target),this.validateLength(t.target),await this.validateInput(t.target),this.showInputErrors(t.target))}inputInputHandler(t){const r=t.target;this.shouldSkipValidation(r)||(o.isType(r,"integer")&&(r.value=o.parseInteger(r.value)),r.type!=="number"&&o.isType(r,["number","float","decimal"])&&(r.value=o.parseNumber(r.value)),o.isType(r,"color")&&this.syncColorInput(t))}syncColorInput(t){let r=t.target,n=r;r.type==="color"&&(n=this.form.querySelector(`#${r.id.replace(/-color/,"")}`));let l=this.form.querySelector(`#${n.id}-color-label`);if((r.dataset.type||"")==="color"){let g=this.form.querySelector(`input#${r.id}-color`);if(!g||!o.isColor(r.value))return;g.value=o.parseColor(r.value)}r.type==="color"&&(n.value=r.value),l&&(l.style.backgroundColor=r.value),clearTimeout(this.dispatchTimeout),this.dispatchTimeout=window.setTimeout(()=>{n.dispatchEvent(new Event("change",{bubbles:!0}))},200)}inputKeydownHandler(t){t.target instanceof HTMLInputElement&&o.isType(t.target,"integer")&&(t.key==="ArrowUp"?(t.preventDefault(),t.target.value===""&&(t.target.value="0"),t.target.value=(parseInt(t.target.value)+1).toString()):t.key==="ArrowDown"&&(parseInt(t.target.value)>0?t.target.value=(parseInt(t.target.value)-1).toString():t.target.value="0"))}destroy(){this.removeEventListeners(),this.originalNoValidate||this.form.removeAttribute("novalidate")}}return H});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jdlien/validator",
3
- "version": "1.3.3",
3
+ "version": "1.3.4",
4
4
  "type": "module",
5
5
  "module": "dist/validator.js",
6
6
  "types": "dist/Validator.d.ts",