@jdlien/validator 1.0.7 → 1.1.6
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 +1 -1
- package/dist/Validator.d.ts +116 -0
- package/dist/validator.js +1 -1
- package/package.json +14 -15
- package/src/Validator.ts +0 -628
- package/src/types.d.ts +0 -23
- package/src/validator-utils.ts +0 -656
package/README.md
CHANGED
|
@@ -299,4 +299,4 @@ Module did not self-register: '...\node_modules\canvas\build\Release\canvas.node
|
|
|
299
299
|
```
|
|
300
300
|
|
|
301
301
|
If that happens, you
|
|
302
|
-
need to install the canvas module manually: `
|
|
302
|
+
need to install the canvas module manually: `npm rebuild canvas --update-binary`
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Form Validator used by EPL apps and www2.
|
|
3
|
+
* © 2023 JD Lien
|
|
4
|
+
*
|
|
5
|
+
* @format
|
|
6
|
+
*/
|
|
7
|
+
export type FormControl = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
|
|
8
|
+
export interface ValidatorOptions {
|
|
9
|
+
messages?: object;
|
|
10
|
+
debug?: boolean;
|
|
11
|
+
autoInit?: boolean;
|
|
12
|
+
preventSubmit?: boolean;
|
|
13
|
+
hiddenClasses?: string;
|
|
14
|
+
errorMainClasses?: string;
|
|
15
|
+
errorInputClasses?: string;
|
|
16
|
+
validationSuccessCallback?: (event: Event) => void;
|
|
17
|
+
validationErrorCallback?: (event: Event) => void;
|
|
18
|
+
}
|
|
19
|
+
export interface InputHandlers {
|
|
20
|
+
[key: string]: {
|
|
21
|
+
parse: (value: string, dateFormat?: string) => string;
|
|
22
|
+
isValid: (value: string) => boolean;
|
|
23
|
+
error: string;
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
export declare class ValidationSuccessEvent extends Event {
|
|
27
|
+
submitEvent: Event;
|
|
28
|
+
constructor(submitEvent: Event);
|
|
29
|
+
}
|
|
30
|
+
export declare class ValidationErrorEvent extends Event {
|
|
31
|
+
submitEvent: Event;
|
|
32
|
+
constructor(submitEvent: Event);
|
|
33
|
+
}
|
|
34
|
+
export default class Validator {
|
|
35
|
+
form: HTMLFormElement;
|
|
36
|
+
inputs: FormControl[];
|
|
37
|
+
inputErrors: {
|
|
38
|
+
[key: string]: string[];
|
|
39
|
+
};
|
|
40
|
+
messages: {
|
|
41
|
+
ERROR_MAIN: string;
|
|
42
|
+
ERROR_GENERIC: string;
|
|
43
|
+
ERROR_REQUIRED: string;
|
|
44
|
+
OPTION_REQUIRED: string;
|
|
45
|
+
CHECKED_REQUIRED: string;
|
|
46
|
+
ERROR_MAXLENGTH: string;
|
|
47
|
+
ERROR_MINLENGTH: string;
|
|
48
|
+
ERROR_NUMBER: string;
|
|
49
|
+
ERROR_INTEGER: string;
|
|
50
|
+
ERROR_TEL: string;
|
|
51
|
+
ERROR_EMAIL: string;
|
|
52
|
+
ERROR_ZIP: string;
|
|
53
|
+
ERROR_POSTAL: string;
|
|
54
|
+
ERROR_DATE: string;
|
|
55
|
+
ERROR_DATE_PAST: string;
|
|
56
|
+
ERROR_DATE_FUTURE: string;
|
|
57
|
+
ERROR_DATE_RANGE: string;
|
|
58
|
+
ERROR_TIME: string;
|
|
59
|
+
ERROR_TIME_RANGE: string;
|
|
60
|
+
ERROR_URL: string;
|
|
61
|
+
ERROR_COLOR: string;
|
|
62
|
+
ERROR_CUSTOM_VALIDATION: string;
|
|
63
|
+
};
|
|
64
|
+
debug: boolean;
|
|
65
|
+
autoInit: boolean;
|
|
66
|
+
preventSubmit: boolean;
|
|
67
|
+
hiddenClasses: string;
|
|
68
|
+
errorMainClasses: string;
|
|
69
|
+
errorInputClasses: string;
|
|
70
|
+
private dispatchTimeout;
|
|
71
|
+
private originalNoValidate;
|
|
72
|
+
private validationSuccessCallback;
|
|
73
|
+
private validationErrorCallback;
|
|
74
|
+
constructor(form: HTMLFormElement, options?: ValidatorOptions);
|
|
75
|
+
private submitHandlerRef;
|
|
76
|
+
private inputInputHandlerRef;
|
|
77
|
+
private inputChangeHandlerRef;
|
|
78
|
+
private inputKeydownHandlerRef;
|
|
79
|
+
addEventListeners(): void;
|
|
80
|
+
removeEventListeners(): void;
|
|
81
|
+
init(): void;
|
|
82
|
+
private getErrorEl;
|
|
83
|
+
private addErrorMain;
|
|
84
|
+
private addInputError;
|
|
85
|
+
private showInputErrors;
|
|
86
|
+
private showFormErrors;
|
|
87
|
+
private clearInputErrors;
|
|
88
|
+
private clearFormErrors;
|
|
89
|
+
private validateRequired;
|
|
90
|
+
private validateLength;
|
|
91
|
+
private inputHandlers;
|
|
92
|
+
private validateInputType;
|
|
93
|
+
private validateDateRange;
|
|
94
|
+
private validatePattern;
|
|
95
|
+
/**
|
|
96
|
+
* Specify a custom function in data-validation and it gets called to validate the input
|
|
97
|
+
* The custom function can return
|
|
98
|
+
* - a boolean
|
|
99
|
+
* - a Promise that resolves to a boolean
|
|
100
|
+
* - an object with a valid property that is a boolean
|
|
101
|
+
* - a Promise that resolves to an object with a valid property that is a boolean
|
|
102
|
+
* - and optionally a messages property that is a string or array of strings
|
|
103
|
+
* - OR optionally, a message property that is a string
|
|
104
|
+
* - optionaly, a boolean error property that is true if something went wrong
|
|
105
|
+
*/
|
|
106
|
+
private validateCustom;
|
|
107
|
+
private validateInput;
|
|
108
|
+
validate(_e?: Event): Promise<boolean>;
|
|
109
|
+
private isSubmitting;
|
|
110
|
+
private submitHandler;
|
|
111
|
+
private inputChangeHandler;
|
|
112
|
+
private inputInputHandler;
|
|
113
|
+
private syncColorInput;
|
|
114
|
+
private inputKeydownHandler;
|
|
115
|
+
destroy(): void;
|
|
116
|
+
}
|
package/dist/validator.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(m,c){typeof exports=="object"&&typeof module<"u"?c(exports):typeof define=="function"&&define.amd?define(["exports"],c):(m=typeof globalThis<"u"?globalThis:m||self,c(m.Validator={}))})(this,function(m){"use strict";var Q=Object.defineProperty;var X=(m,c,f)=>c in m?Q(m,c,{enumerable:!0,configurable:!0,writable:!0,value:f}):m[c]=f;var d=(m,c,f)=>(X(m,typeof c!="symbol"?c+"":c,f),f);function c(r){return r instanceof HTMLInputElement||r instanceof HTMLSelectElement||r instanceof HTMLTextAreaElement}function f(r,e){typeof e=="string"&&(e=[e]);const t=r.dataset.type||"",i=r.type||"";return!!(e.includes(t)||e.includes(i))}function Z(r){return r.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 L(r){const e=parseInt(r);if(typeof r=="number"||!isNaN(e))return e-1;const t=new Date(`1 ${r} 2000`).getMonth();if(!isNaN(t))return t;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 s in i)if(r.toLowerCase().startsWith(s))return i[s];throw new Error("Invalid month name: "+r)}function b(r){return typeof r=="string"&&(r=parseInt(r.replace(/\D/g,""))),r>99?r:r<(new Date().getFullYear()+20)%100?r+2e3:r+1900}function p(r){if(r instanceof Date)return r;r=r.trim().toLowerCase();let e=0,t=0,i=0,s=0,a=0,n=0;const l=new RegExp(/\d{1,2}\:\d\d(?:\:\d\ds?)?\s?(?:[a|p]m?)?/gi);if(l.test(r)){const h=r.match(l)[0];r=r.replace(h,"").trim();const g=E(h);if(g!==null&&({hour:s,minute:a,second:n}=g),r.length<=2){const M=new Date;return new Date(M.getFullYear(),M.getMonth(),M.getDate(),s,a,n)}}const u=/(^|\b)(mo|tu|we|th|fr|sa|su|lu|mard|mer|jeu|ve|dom)[\w]*\.?/gi;r=r.replace(u,"").trim();const o=new Date(new Date().setHours(0,0,0,0));if(/(now|today)/.test(r))return o;if(r.includes("tomorrow"))return new Date(o.setDate(o.getDate()+1));r.length===8&&(r=r.replace(/(\d\d\d\d)(\d\d)(\d\d)/,"$1-$2-$3")),r.length===6&&(r=r.replace(/(\d\d)(\d\d)(\d\d)/,b(r.slice(0,2))+"-$2-$3"));try{({year:e,month:t,day:i}=j(r))}catch{return new Date("")}return new Date(e,t-1,i,s,a,n)}function j(r){function e(n,l=[null,null,null]){const u=o=>o.filter(h=>!l.includes(h));return n===0||n>31?u(["y"]):n>12?u(["d","y"]):n>=1||n<=12?u(["m","d","y"]):[]}const t=r.split(/[\s-/:.,]+/).filter(n=>n!=="");if(t.length<3){if(r.match(/\d{4}/)!==null)throw new Error("Invalid Date");t.unshift(String(new Date().getFullYear()))}const i={year:0,month:0,day:0};function s(n,l){n==="year"?i.year=b(l):i[n]=l}let a=0;for(;!(i.year&&i.month&&i.day);){e:for(const n of t){if(a++,/^[a-zA-Zé]+$/.test(n)){i.month||s("month",L(n)+1);continue}if(/^'\d\d$/.test(n)||/^\d{3,5}$/.test(n)){i.year||s("year",parseInt(n.replace(/'/,"")));continue}const l=parseInt(n);if(isNaN(l))throw console.error(`not date because ${n} isNaN`),new Error("Invalid Date");const u=e(l,[i.year?"y":null,i.month?"m":null,i.day?"d":null]);if(u.length==1)for(let o=0;o<u.length;o++){if(u[o]==="m"&&!i.month){s("month",l);continue e}if(u[o]==="d"&&!i.day){s("day",l);continue e}if(u[o]==="y"&&!i.year){s("year",l);continue e}}a>3&&(!i.month&&u.includes("m")?s("month",l):!i.day&&u.includes("d")?s("day",l):!i.year&&u.includes("y")&&s("year",l))}if(a>6)throw new Error("Invalid Date")}if(i.year&&i.month&&i.day)return i;throw new Error("Invalid Date")}function E(r){if(r=r.trim().toLowerCase(),r==="now"){const o=new Date;return{hour:o.getHours(),minute:o.getMinutes(),second:o.getSeconds()}}const e=r.match(/(\d{3,4})/);if(e){const o=e[1].length,h=e[1].slice(0,o==3?1:2),g=e[1].slice(-2);r=r.replace(e[1],h+":"+g)}const t=new RegExp(/^(\d{1,2})(?::(\d{1,2}))?\s*(?:(a|p)m?)?$/i);if(t.test(r)){const o=r.match(t);if(o===null)return null;r=o[1]+":"+(o[2]||"00")+(o[3]||"")}const i=new RegExp(/^(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?\s*(?:(a|p)m?)?$/i);if(!i.test(r))return null;const s=r.match(i);if(s===null)return null;const a=parseInt(s[1]),n=parseInt(s[2]),l=s[3]?parseInt(s[3]):0,u=s[4];return isNaN(a)||isNaN(n)||isNaN(l)?null:u==="p"&&a<12?{hour:a+12,minute:n,second:l}:u==="a"&&a===12?{hour:0,minute:n,second:l}:a<0||a>23||n<0||n>59||l<0||l>59?null:{hour:a,minute:n,second:l}}function S(r,e="h:mm A"){const t=E(r);if(t){const i=new Date;return i.setHours(t.hour),i.setMinutes(t.minute),i.setSeconds(t.second),i.setMilliseconds(0),y(i,e)}return""}function y(r,e="YYYY-MM-DD"){if(r=p(r),isNaN(r.getTime()))return"";const t={y:r.getFullYear(),M:r.getMonth(),D:r.getDate(),W:r.getDay(),H:r.getHours(),m:r.getMinutes(),s:r.getSeconds(),ms:r.getMilliseconds()},i=(o,h=2)=>(o+"").padStart(h,"0"),s=()=>t.H%12||12,a=o=>o<12?"AM":"PM",n=o=>"January|February|March|April|May|June|July|August|September|October|November|December".split("|")[o];function l(o,h=0){const g="Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday".split("|");return h?g[o].slice(0,h):g[o]}const u={YY:String(t.y).slice(-2),YYYY:t.y,M:t.M+1,MM:i(t.M+1),MMMM:n(t.M),MMM:n(t.M).slice(0,3),D:String(t.D),DD:i(t.D),d:String(t.W),dd:l(t.W,2),ddd:l(t.W,3),dddd:l(t.W),H:String(t.H),HH:i(t.H),h:s(),hh:i(s()),A:a(t.H),a:a(t.H).toLowerCase(),m:String(t.m),mm:i(t.m),s:String(t.s),ss:i(t.s),SSS:i(t.ms,3)};return e.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,(o,h)=>h||u[o])}function D(r,e){const t=p(r);return isNaN(t.getTime())?"":((!e||e.length===0)&&(e="YYYY-MMM-DD"),y(t,e))}function C(r){let e=p(r);return e==null?!1:!isNaN(e.getTime())}function x(r,e){return!(e==="past"&&r>new Date||e==="future"&&r.getTime()<new Date().setHours(0,0,0,0))}function H(r){let e=E(r);return e===null?!1:!isNaN(e.hour)&&!isNaN(e.minute)&&!isNaN(e.second)}function A(r){if(r.length>255||!new RegExp(/^.+@.+\.[a-zA-Z0-9]{2,}$/).test(r))return!1;let t="";return t+="^([a-zA-Z0-9!#$%'*+/=?^_`{|}~-]+",t+="(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*",t+="|",t+='"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*"',t+=")@(",t+="(",t+="(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+",t+="[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?",t+=")",t+=")$",new RegExp(t).test(r)}function N(r){return r=r.replace(/^[^2-90]+/g,""),r=r.replace(/(\d\d\d).*?(\d\d\d).*?(\d\d\d\d)(.*)/,"$1-$2-$3$4"),r}function O(r){return/^\d\d\d-\d\d\d-\d\d\d\d$/.test(r)}function v(r){return r.replace(/[^0-9]/g,"")}function _(r){return/^\-?\d*\.?\d*$/.test(r)}function w(r){return r.replace(/[^\-0-9.]/g,"").replace(/(^-)|(-)/g,(e,t)=>t?"-":"").replace(/(\..*)\./g,"$1")}function k(r){return/^\-?\d*$/.test(r)}function $(r){return r=r.trim(),new RegExp("^(?:[a-z+]+:)?//","i").test(r)?r:"https://"+r}function P(r){return new RegExp("^(?:[-a-z+]+:)?//","i").test(r)}function Y(r){return r=r.replace(/[^0-9]/g,"").replace(/(.{5})(.*)/,"$1-$2").trim(),r.length===6&&(r=r.replace(/-/,"")),r}function V(r){return new RegExp(/^\d{5}(-\d{4})?$/).test(r)}function U(r){return r=r.toUpperCase().replace(/[^A-Z0-9]/g,"").replace(/(.{3})\s*(.*)/,"$1 $2").trim(),r}function F(r){return new RegExp(/^[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ] ?[0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]$/).test(r)}function T(r){return["transparent","currentColor"].includes(r)?!0:typeof r!="string"||!r.trim()?!1:typeof CSS=="object"&&typeof CSS.supports=="function"?CSS.supports("color",r):G(r)}function G(r){const e=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*\)$/),t=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*\)$/),s=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*\)$/),a=new RegExp(/^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);let n="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 l=new RegExp(`^(${n})$`,"i");return e.test(r)||t.test(r)||i.test(r)||s.test(r)||a.test(r)||l.test(r)}let R=null;const I=new Map;function q(r){if(r=r.trim().toLowerCase(),r==="transparent")return"transparent";if(I.has(r))return I.get(r);R===null&&(R=document.createElement("canvas"),R.willReadFrequently=!0);let e=R.getContext("2d");if(!e)throw new Error("Can't get context from colorCanvas");e.fillStyle=r,e.fillRect(0,0,1,1);let t=e.getImageData(0,0,1,1).data,i="#"+("000000"+(t[0]<<16|t[1]<<8|t[2]).toString(16)).slice(-6);return I.set(r,i),i}function z(r){let e={valid:!1,error:!1,messages:[]};return typeof r=="boolean"?{valid:r,error:!1,messages:[]}:typeof r=="string"?{valid:!1,error:!1,messages:[r]}:(typeof r.valid=="boolean"&&(e.valid=r.valid),typeof r.message=="string"&&(e.messages=[r.message]),typeof r.messages=="string"&&(e.messages=[r.messages]),Array.isArray(r.messages)&&(e.messages=r.messages),r.error===!0&&(e.error=!0),e)}const K=Object.freeze(Object.defineProperty({__proto__:null,formatDateTime:y,isColor:T,isDate:C,isDateInRange:x,isEmail:A,isFormControl:c,isInteger:k,isNANPTel:O,isNumber:_,isPostalCA:F,isTime:H,isType:f,isUrl:P,isZip:V,momentToFPFormat:Z,monthToNumber:L,normalizeValidationResult:z,parseColor:q,parseDate:p,parseDateToString:D,parseInteger:v,parseNANPTel:N,parseNumber:w,parsePostalCA:U,parseTime:E,parseTimeToString:S,parseUrl:$,parseZip:Y,yearToFull:b},Symbol.toStringTag,{value:"Module"}));class W extends Event{constructor(t){super("validationSuccess",{cancelable:!0});d(this,"submitEvent");this.submitEvent=t}}class B extends Event{constructor(t){super("validationError",{cancelable:!0});d(this,"submitEvent");this.submitEvent=t}}class J{constructor(e,t={}){d(this,"form");d(this,"inputs",[]);d(this,"inputErrors",{});d(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."});d(this,"debug");d(this,"autoInit");d(this,"preventSubmit",!1);d(this,"hiddenClasses");d(this,"errorMainClasses");d(this,"errorInputClasses");d(this,"dispatchTimeout",0);d(this,"originalNoValidate",!1);d(this,"validationSuccessCallback");d(this,"validationErrorCallback");d(this,"submitHandlerRef",this.submitHandler.bind(this));d(this,"inputInputHandlerRef",this.inputInputHandler.bind(this));d(this,"inputChangeHandlerRef",this.inputChangeHandler.bind(this));d(this,"inputKeydownHandlerRef",this.inputKeydownHandler.bind(this));d(this,"inputHandlers",{number:{parse:w,isValid:_,error:this.messages.ERROR_NUMBER},integer:{parse:v,isValid:k,error:this.messages.ERROR_INTEGER},tel:{parse:N,isValid:O,error:this.messages.ERROR_TEL},email:{parse:e=>e.trim(),isValid:A,error:this.messages.ERROR_EMAIL},zip:{parse:Y,isValid:V,error:this.messages.ERROR_ZIP},postal:{parse:U,isValid:F,error:this.messages.ERROR_POSTAL},url:{parse:$,isValid:P,error:this.messages.ERROR_URL},date:{parse:D,isValid:C,error:this.messages.ERROR_DATE},time:{parse:S,isValid:H,error:this.messages.ERROR_TIME},color:{parse:e=>e.trim().toLowerCase(),isValid:T,error:this.messages.ERROR_COLOR}});d(this,"isSubmitting",!1);if(!e)throw new Error("Validator requires a form to be passed as the first argument.");if(!(e instanceof HTMLFormElement))throw new Error("form argument must be an instance of HTMLFormElement");this.form=e,(e.dataset.preventSubmit===""||e.dataset.preventSubmit)&&(this.preventSubmit=!0),Object.assign(this.messages,t.messages||{}),this.debug=t.debug||!1,this.autoInit=t.autoInit!==!1,this.preventSubmit=t.preventSubmit===!1?!1:this.preventSubmit,this.hiddenClasses=t.hiddenClasses||"hidden opacity-0",this.errorMainClasses=t.errorMainClasses||"m-2 border border-red-500 bg-red-100 p-3 dark:bg-red-900/80 text-center",this.errorInputClasses=t.errorInputClasses||"border-red-600 dark:border-red-500",this.validationSuccessCallback=t.validationSuccessCallback||(()=>{}),this.validationErrorCallback=t.validationErrorCallback||(()=>{}),this.autoInit&&this.init(),new MutationObserver(()=>this.autoInit&&this.init()).observe(e,{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(e=>{!e.name&&!e.id&&(e.id=`vl-input-${Math.random().toString(36).slice(2)}`),this.inputErrors[e.name||e.id]=[]}),this.originalNoValidate=this.form.hasAttribute("novalidate"),this.form.setAttribute("novalidate","novalidate"),this.removeEventListeners(),this.addEventListeners()}getErrorEl(e){const t=document.getElementById(e.name+"-error");return t||document.getElementById(e.id+"-error")||null}addErrorMain(e){const t=document.createElement("div");t.id="form-error-main",this.errorMainClasses.split(" ").forEach(i=>{t.classList.add(i)}),e?t.innerHTML=e:t.innerHTML=this.messages.ERROR_MAIN,this.form.appendChild(t)}addInputError(e,t=e.dataset.errorDefault||this.messages.ERROR_GENERIC){const i=e.name||e.id;this.debug&&console.log("Invalid value for "+i+": "+t),i in this.inputErrors||(this.inputErrors[i]=[]),this.inputErrors[i].includes(t)||this.inputErrors[i].push(t)}showInputErrors(e){if(!e||!e.name&&!e.id)return;const t=e.name||e.id,i=t in this.inputErrors?this.inputErrors[t]:[];if(!i.length)return;e.setAttribute("aria-invalid","true"),this.errorInputClasses.split(" ").forEach(a=>{e.classList.add(a)});let s=this.getErrorEl(e);s&&(s.innerHTML=i.join("<br>"),this.hiddenClasses.split(" ").forEach(a=>{s&&s.classList.remove(a)}))}showFormErrors(){if(this.inputs.forEach(e=>this.showInputErrors(e)),Object.values(this.inputErrors).some(e=>Array.isArray(e)&&e.length)){const e=this.form.querySelectorAll("#form-error-main");e.length?e.forEach(t=>{t.innerHTML||(t.innerHTML=this.messages.ERROR_MAIN),this.hiddenClasses.split(" ").forEach(i=>{t.classList.remove(i)})}):this.addErrorMain()}}clearInputErrors(e){this.inputErrors[e.name||e.id]=[],e.removeAttribute("aria-invalid");let t=this.getErrorEl(e);t&&(this.errorInputClasses.split(" ").forEach(i=>{e.classList.remove(i)}),this.hiddenClasses.split(" ").forEach(i=>{t&&t.classList.add(i)}),t.textContent="")}clearFormErrors(){this.form.querySelectorAll("#form-error-main").forEach(e=>{this.hiddenClasses.split(" ").forEach(t=>{e.classList.add(t)})}),this.inputs.forEach(e=>this.clearInputErrors(e))}validateRequired(e){let t=!0;if(e.required&&(e.value===""||e instanceof HTMLInputElement&&["checkbox","radio"].includes(e.type)&&!e.checked))if(e instanceof HTMLInputElement&&["checkbox","radio"].includes(e.type)){let i=!1,s=e.name;const a=this.form.querySelectorAll(`input[name="${s}"]`);if(a.forEach(n=>{if(n instanceof HTMLInputElement&&n.checked===!0){i=!0;return}}),i===!1){t=!1;let n=a.length>1?this.messages.OPTION_REQUIRED:this.messages.CHECKED_REQUIRED;e.dataset.errorDefault&&(n=e.dataset.errorDefault),this.addInputError(e,n)}}else c(e)&&(t=!1,this.addInputError(e,e.dataset.errorDefault||this.messages.ERROR_REQUIRED));return t}validateLength(e){let t=!0;if((e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)&&e.value.length){let i=e.minLength>0?e.minLength:e.dataset.minLength?parseInt(e.dataset.minLength):0,s=e.maxLength>0&&e.maxLength<5e5?e.maxLength:e.dataset.maxLength?parseInt(e.dataset.maxLength):1/0;i>0&&e.value.length<i&&(t=!1,this.addInputError(e,this.messages.ERROR_MINLENGTH.replace("${val}",i.toString()))),e.value.length>s&&(t=!1,this.addInputError(e,this.messages.ERROR_MAXLENGTH.replace("${val}",s.toString())))}return t}validateInputType(e){const t=e.dataset.type||e.type,i=this.inputHandlers[e.type]||this.inputHandlers[t];if(i){const s=e.dataset.dateFormat||e.dataset.timeFormat,a=i.parse(e.value,s),n=["date","time","datetime-local","month","week"];if(a.length&&!n.includes(e.type)&&(e.value=a),!i.isValid(e.value))return this.addInputError(e,i.error),!1}return!0}validateDateRange(e){if(e.dataset.dateRange){const t=e.dataset.dateRange,i=p(e.value);if(!isNaN(i.getTime())&&!x(i,t)){let s=e.dataset.errorDefault||this.messages.ERROR_DATE_RANGE;return t==="past"?s=this.messages.ERROR_DATE_PAST:t==="future"&&(s=this.messages.ERROR_DATE_FUTURE),this.addInputError(e,s),!1}}return!0}validatePattern(e){const t=e.dataset.pattern||e instanceof HTMLInputElement&&e.pattern||null;return t&&!new RegExp(t).test(e.value)?(this.addInputError(e),!1):!0}async validateCustom(e){const t=e.dataset.validation;if(!t||typeof t!="string")return!0;const i=window[t];if(!i||typeof i!="function")return!0;let s;try{s=await Promise.resolve(i(e.value)),s=z(s)}catch{return this.addInputError(e,this.messages.ERROR_CUSTOM_VALIDATION),!1}const a=s.messages.join("<br>")||this.messages.ERROR_CUSTOM_VALIDATION;return s.valid||this.addInputError(e,a),s.valid}async validateInput(e){if(!(e instanceof HTMLInputElement)||!e.value.length)return!0;let t=!0;return t=this.validateInputType(e)&&t,t=this.validateDateRange(e)&&t,t=this.validatePattern(e)&&t,t=await this.validateCustom(e)&&t,t}async validate(e){let t=!0;for(const i of this.inputs)t=this.validateRequired(i)&&t,t=this.validateLength(i)&&t,t=await this.validateInput(i)&&t;return t}async submitHandler(e){if(this.isSubmitting)return;e.preventDefault(),this.clearFormErrors();let t=await this.validate(e);this.showFormErrors();const i=new W(e),s=new B(e);t?(this.form.dispatchEvent(i),this.validationSuccessCallback&&this.validationSuccessCallback(e)):(this.form.dispatchEvent(s),this.validationErrorCallback&&this.validationErrorCallback(e)),t&&!this.preventSubmit&&(this.isSubmitting=!0,i.defaultPrevented||this.form.submit(),this.isSubmitting=!1)}async inputChangeHandler(e){e.target instanceof HTMLInputElement&&(this.clearInputErrors(e.target),await this.validateInput(e.target),this.showInputErrors(e.target))}inputInputHandler(e){const t=e.target;f(t,"integer")&&(t.value=v(t.value)),t.type!=="number"&&f(t,["number","float","decimal"])&&(t.value=w(t.value)),f(t,"color")&&this.syncColorInput(e)}syncColorInput(e){let t=e.target,i=t;t.type==="color"&&(i=this.form.querySelector(`#${t.id.replace(/-color/,"")}`));let s=this.form.querySelector(`#${i.id}-color-label`);if((t.dataset.type||"")==="color"){let a=this.form.querySelector(`input#${t.id}-color`);if(!a||!T(t.value))return;a.value=q(t.value)}t.type==="color"&&(i.value=t.value),s&&(s.style.backgroundColor=t.value),clearTimeout(this.dispatchTimeout),this.dispatchTimeout=window.setTimeout(()=>{i.dispatchEvent(new Event("change",{bubbles:!0}))},200)}inputKeydownHandler(e){e.target instanceof HTMLInputElement&&f(e.target,"integer")&&(e.key==="ArrowUp"?(e.preventDefault(),e.target.value===""&&(e.target.value="0"),e.target.value=(parseInt(e.target.value)+1).toString()):e.key==="ArrowDown"&&(parseInt(e.target.value)>0?e.target.value=(parseInt(e.target.value)-1).toString():e.target.value="0"))}destroy(){this.removeEventListeners(),this.originalNoValidate||this.form.removeAttribute("novalidate")}}m.default=J,m.validatorUtils=K,Object.defineProperties(m,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
|
1
|
+
(function(f,i){typeof exports=="object"&&typeof module<"u"?module.exports=i():typeof define=="function"&&define.amd?define(i):(f=typeof globalThis<"u"?globalThis:f||self,f.Validator=i())})(this,function(){"use strict";var ae=Object.defineProperty;var se=(f,i,v)=>i in f?ae(f,i,{enumerable:!0,configurable:!0,writable:!0,value:v}):f[i]=v;var m=(f,i,v)=>(se(f,typeof i!="symbol"?i+"":i,v),v);var f=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},i={},v={get exports(){return i},set exports(w){i=w}};(function(w,t){(function(r,n){n(t)})(f,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||"",o=e.type;return!!(s.includes(a)||s.includes(o))}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 E(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 o={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 o)if(e.toLowerCase().startsWith(h))return o[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 T(e){if(e instanceof Date)return e;e=e.trim().toLowerCase();let s=0,a=0,o=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=I(R);if(y!==null&&({hour:h,minute:d,second:u}=y),e.length<=2){const S=new Date;return new Date(S.getFullYear(),S.getMonth(),S.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:o}=k(e))}catch{return new Date("")}return new Date(s,a-1,o,h,d,u)}function O(e,s=[null,null,null]){const a=o=>o.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 k(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 o(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||o("month",E(d)+1);continue}if(/^'\d\d$/.test(d)||/^\d{3,5}$/.test(d)){a.year||o("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=O(u,[a.year?"y":null,a.month?"m":null,a.day?"d":null]);if(p.length==1){if(p[0]==="m"&&!a.month){o("month",u);continue e}if(p[0]==="d"&&!a.day){o("day",u);continue e}if(p[0]==="y"&&!a.year){o("year",u);continue e}}h>3&&(!a.month&&p.includes("m")?o("month",u):!a.day&&p.includes("d")&&o("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 I(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 o=new RegExp(/^(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?\s*(?:(a|p)m?)?$/i);if(!o.test(e))return null;const h=e.match(o);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=I(e);if(a){const o=new Date;return o.setHours(a.hour),o.setMinutes(a.minute),o.setSeconds(a.second),o.setMilliseconds(0),D(o,s)}return""}function D(e,s="YYYY-MM-DD"){if(e=T(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()},o=(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:o(a.M+1),MMMM:u(a.M),MMM:u(a.M).slice(0,3),D:String(a.D),DD:o(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:o(a.H),h:h(),hh:o(h()),A:d(a.H),a:d(a.H).toLowerCase(),m:String(a.m),mm:o(a.m),s:String(a.s),ss:o(a.s),SSS:o(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=T(e);return isNaN(a.getTime())?"":((!s||s.length===0)&&(s="YYYY-MMM-DD"),D(a,s))}function $(e){if(typeof e!="string"&&!(e instanceof Date))return!1;let s=T(e);return s==null?!1:!isNaN(s.getTime())}function Y(e,s){return!(s==="past"&&e>new Date||s==="future"&&e.getTime()<new Date().setHours(0,0,0,0))}function V(e){let s=I(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 W(e){return e=e.replace(/[^0-9]/g,"").replace(/(.{5})(.*)/,"$1-$2").trim(),e.length===6&&(e=e.replace(/-/,"")),e}function B(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*\)$/),o=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)||o.test(e)||h.test(e)||d.test(e)||p.test(e)}let M=null;const C=new Map;function te(e){if(e=e.trim().toLowerCase(),["transparent","currentcolor"].includes(e))return e;if(C.has(e))return C.get(e);M===null&&(M=document.createElement("canvas"),M.willReadFrequently=!0);let s=M.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,o="#"+("000000"+(a[0]<<16|a[1]<<8|a[2]).toString(16)).slice(-6);return C.set(e,o),o}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=D,r.isColor=X,r.isDate=$,r.isDateInRange=Y,r.isEmail=P,r.isFormControl=n,r.isInteger=G,r.isNANPTel=F,r.isNumber=Z,r.isPostalCA=Q,r.isTime=V,r.isType=l,r.isUrl=K,r.isZip=B,r.momentToFPFormat=g,r.monthToNumber=E,r.normalizeValidationResult=re,r.parseColor=te,r.parseDate=T,r.parseDateToString=x,r.parseInteger=q,r.parseNANPTel=U,r.parseNumber=z,r.parsePostalCA=J,r.parseTime=I,r.parseTimeToString=_,r.parseUrl=j,r.parseZip=W,r.yearToFull=L,Object.defineProperty(r,Symbol.toStringTag,{value:"Module"})})})(v,i);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:i.parseNumber,isValid:i.isNumber,error:this.messages.ERROR_NUMBER},integer:{parse:i.parseInteger,isValid:i.isInteger,error:this.messages.ERROR_INTEGER},tel:{parse:i.parseNANPTel,isValid:i.isNANPTel,error:this.messages.ERROR_TEL},email:{parse:t=>t.trim(),isValid:i.isEmail,error:this.messages.ERROR_EMAIL},zip:{parse:i.parseZip,isValid:i.isZip,error:this.messages.ERROR_ZIP},postal:{parse:i.parsePostalCA,isValid:i.isPostalCA,error:this.messages.ERROR_POSTAL},url:{parse:i.parseUrl,isValid:i.isUrl,error:this.messages.ERROR_URL},date:{parse:i.parseDateToString,isValid:i.isDate,error:this.messages.ERROR_DATE},time:{parse:i.parseTimeToString,isValid:i.isTime,error:this.messages.ERROR_TIME},color:{parse:t=>t.trim().toLowerCase(),isValid:i.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===!1?!1: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");return r||document.getElementById(t.id+"-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(E=>{if(E instanceof HTMLInputElement&&E.checked===!0){n=!0;return}}),n===!1){r=!1;let E=g.length>1?this.messages.OPTION_REQUIRED:this.messages.CHECKED_REQUIRED;t.dataset.errorDefault&&(E=t.dataset.errorDefault),this.addInputError(t,E)}}else i.isFormControl(t)&&(r=!1,this.addInputError(t,t.dataset.errorDefault||this.messages.ERROR_REQUIRED));return r}validateLength(t){let r=!0;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),E=["date","time","datetime-local","month","week"];if(g.length&&!E.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=i.parseDate(t.value);if(!isNaN(n.getTime())&&!i.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){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=i.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 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)r=this.validateRequired(n)&&r,r=this.validateLength(n)&&r,r=await this.validateInput(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)}async inputChangeHandler(t){t.target instanceof HTMLInputElement&&(this.clearInputErrors(t.target),await this.validateInput(t.target),this.showInputErrors(t.target))}inputInputHandler(t){const r=t.target;i.isType(r,"integer")&&(r.value=i.parseInteger(r.value)),r.type!=="number"&&i.isType(r,["number","float","decimal"])&&(r.value=i.parseNumber(r.value)),i.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||!i.isColor(r.value))return;g.value=i.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&&i.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,20 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jdlien/validator",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.6",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"module": "dist/validator.js",
|
|
6
|
+
"types": "dist/Validator.d.ts",
|
|
6
7
|
"files": [
|
|
7
|
-
"dist"
|
|
8
|
-
"src"
|
|
8
|
+
"dist"
|
|
9
9
|
],
|
|
10
|
-
"description": "Validates and sanitizes the inputs in a form using native
|
|
10
|
+
"description": "Validates and sanitizes the inputs in a form using native HTML attributes.",
|
|
11
11
|
"scripts": {
|
|
12
12
|
"dev": "vite",
|
|
13
|
-
"build": "tsc &&
|
|
13
|
+
"build": "vite build && tsc --emitDeclarationOnly && tailwindcss -i demo/demo-src.css -o demo/demo.css -m",
|
|
14
14
|
"preview": "vite preview",
|
|
15
15
|
"test": "vitest",
|
|
16
16
|
"coverage": "vitest --coverage",
|
|
17
|
-
"tw": "tailwindcss -i demo-src.css -o demo.css -w -m"
|
|
17
|
+
"tw": "tailwindcss -i demo/demo-src.css -o demo/demo.css -w -m"
|
|
18
18
|
},
|
|
19
19
|
"repository": {
|
|
20
20
|
"type": "git",
|
|
@@ -27,19 +27,14 @@
|
|
|
27
27
|
"form",
|
|
28
28
|
"validation",
|
|
29
29
|
"front-end",
|
|
30
|
-
"validation",
|
|
31
30
|
"better",
|
|
32
31
|
"HTML",
|
|
33
32
|
"inputs",
|
|
34
33
|
"date",
|
|
35
|
-
"validation",
|
|
36
34
|
"time",
|
|
37
|
-
"validation",
|
|
38
35
|
"color",
|
|
39
|
-
"validation",
|
|
40
36
|
"required",
|
|
41
|
-
"field"
|
|
42
|
-
"validation"
|
|
37
|
+
"field"
|
|
43
38
|
],
|
|
44
39
|
"author": "JD Lien",
|
|
45
40
|
"license": "ISC",
|
|
@@ -51,14 +46,18 @@
|
|
|
51
46
|
"@sheerun/mutationobserver-shim": "^0.3.3",
|
|
52
47
|
"@tailwindcss/forms": "^0.5.3",
|
|
53
48
|
"@types/jsdom": "^21.1.0",
|
|
54
|
-
"@vitest/coverage-c8": "^0.
|
|
49
|
+
"@vitest/coverage-c8": "^0.29.1",
|
|
50
|
+
"canvas": "^2.11.0",
|
|
55
51
|
"jsdom": "^21.1.0",
|
|
56
52
|
"jsdom-global": "^3.0.2",
|
|
57
53
|
"prettier": "^2.8.4",
|
|
58
54
|
"tailwindcss": "^3.2.7",
|
|
59
55
|
"typescript": "^4.9.3",
|
|
60
56
|
"vite": "^4.1.0",
|
|
61
|
-
"vitest": "^0.
|
|
57
|
+
"vitest": "^0.29.1"
|
|
62
58
|
},
|
|
63
|
-
"sideEffects": false
|
|
59
|
+
"sideEffects": false,
|
|
60
|
+
"dependencies": {
|
|
61
|
+
"@jdlien/validator-utils": "^1.1.6"
|
|
62
|
+
}
|
|
64
63
|
}
|