UNPKG

formvalidatorplus

Version:

This library offers a complete solution for validating, handling, and submitting forms of all complexities. From simple contact forms to intricate multi-step wizards, FormValidatorPlus empowers web developers to streamline the entire process. It handles

6 lines 27.3 kB
/** * @name FormValidator * @author Muhthishim Malik * https://github.com/Muhthishimiscoding/FormValidatorPlus */ !function(e){"object"==typeof module?module.exports=e:[window.Validator,window.SubmitForm]=e(jQuery)}((function(e){"use strict";if("function"!=typeof e)throw new Error("FormValidatorPlus works with jquery");class t{static errorMessages={alpha:"This field needs to contain only alphabatic characters i.e A to z.",alpha_s:"This field can only have only alphabatic characters i.e A to z and space",alphaNumeric:"This field can only contain alphanumeric characters.",alphaNumeric_s:"Thie fields can only contain alphanumeric characters and space.",barcode:"Please enter a valid barcode (UPC-E, UPC-A, EAN, EAN-14, SSCC).",date:"Please enter a valid date in the format YYYY-DD-MM.",dateAll:"Please enter a valid date",dateTime:"Please enter a valid date and time in the format YYYY-DD-MM HH:MM:SS.",required:"This field is required.",email:"Please provide a valid email address.",min:"The field should contain a minimum of {min} characters.",max:"The field should contain a maximum of {max} characters.",noSpecial:"This field should not contain any special characters like $, #, &, @, or >.",space:"This field must contain at least one space.",noSpace:"This field should not contain any spaces.",lowerCase:"This field should contain lowercase letters.",upperCase:"This field should contain uppercase letters.",numb:"This field should contain only digits.",maxnumb:"This field should not exceed {max} digits.",minnumb:"This field should contain at least {min} digits.",makeInvalidEmpty:"Please make this field empty.",tillDate:"The date of this field should be selected on or before {tillDate}.",shouldOld:"Age Requirement: You must be at least {shouldOld} years old to access this feature/content.",fileSize:"The maximum allowed file size is {fileSize} and your file size is {fileSize2}.",fileType:"The allowed file types are {fileType}",image:"The uploaded file is not a valid image. Allowed image types are {image}.",fileExt:"The file is not of valid type allowed file types are {fileExt}.",dimension_equal:"The uploaded image has a width of {givenWidth}px and height of {givenHeight}px, while the required dimensions are {expectedWidth}x{expectedHeight} pixels.",dimension_smallest:"The smallest accepted width and height are {expectedWidth}x{expectedHeight} pixels, but your image is smaller than that, {givenWidth}x{givenHeight}.",dimension_highest:"The largest accepted width and height are {expectedWidth}x{expectedHeight} pixels, but your image is larger than that, {givenWidth}x{givenHeight}.",dimension_width:"The expected width for this image is {width}px.",dimension_height:"The expected height for this image is {height}px.",dimension_square:"This image needs to be a square, meaning it should have the same height and width, like 500x500 pixels.",dimension_square_size:"This image needs to be square with a width and height of {expectedWidth}x{expectedHeight} pixels.",dimension_aspectRatio:"The image must have an aspect ratio of {aspectRatio}.",detectMultipleSpaces:"This field has multiple consecutive spaces.",accept:"Please check this checkbox.",range:"The entered number must be between {num1} to {num2}.",numb:"This field needs to be a valid number without any space",numb_space:"This field needs to be a valid number.",numb_space_double:"This field contains more spaces then it should.",password:"This field needs to contain small case, uppercase, special characters i.e $,#,% etc and digits characters and has a length of atleast {password} characters.",hasLowerCase:"The field needs to have a lower case character.",hasUpperCase:"The field needs to have a upper case character.",hasSpecial:"The field needs to have a special character like $, #, @, & etc.",hasDigit:"The field needs to have a numeric digit [0-9].",same:"This field must match with the {same}.",inList:"The field must be of any of these {inList}.",url:"Please enter a valid HTTP or HTTPS URL.",url_ftp:"Please enter a valid HTTP or HTTPS or FTP URL.",zipCode:"Please enter a valid ZIP/Postal code.",json:"The provided JSON structure is not valid.",ipv4:"Please enter a valid IPv4 address.",ipv6:"Please enter a valid IPv6 address.",isbn10:"Please enter a valid ISBN-10.",upca:"Please enter a valid UPC-A (Universal Product Code).",ean:"Please enter a valid EAN-10 or EAN-13 (European Article Number)."};static REG_SPECIAL=/[^\p{L}0-9\s.]/u;static defaultMsg="An unknown error occured";static classes=["is-invalid","invalid-feedback"];static imgMimeTypes=["image/jpeg","image/jpg","image/png","image/gif","image/bmp","image/webp"];static changeCssClasses(e){if(2!=e.length)throw Error(`You should give 2 classes to replace default classes which are ${t.classes.join(", ")}.`);t.classes=e}constructor(e,t={},r=null){this.customMessages=t,this.rules=e,this.data=r,this.errors={},this.dateFormat={},this.conerrors={}}regConErrors(e,t){return null==this.conerrors?.[e]?.[t]&&(null==this.conerrors?.[e]&&(this.conerrors[e]={}),this.conerrors[e][t]=new Map),{inp:e,ruleName:t}}static setRegexSpecial(e){t.REG_SPECIAL=e}setRules(e){return this.rules=e,this}setErrorMessages(e){return this.customMessages?this.customMessages={...this.customMessages,...e}:this.customMessages=e,this}static setImgMimeTypes(e){t.imgMimeTypes=e}static get RULE_REQUIRED(){return"required"}static getDate(e){let t;return"number"==typeof e?(t=new Date,t.setFullYear(t.getFullYear()-e),t.setHours(0,0,0,0)):t="string"==typeof e?new Date(e):e instanceof Date?e:new Date,t}static setMaxdate(e,s=null){let i=r.selectElem(e,HTMLInputElement,!0),a=t.getDate(s).toISOString();"date"===i.attr("type")?i[0].max=a.split("T")[0]:i[0].max=a.slice(0,a.lastIndexOf(":"))}static setNum(e,t=!1){let s=r.selectElem(e,HTMLElement,!0);s.on("input",(function(){let e=s.val();s.val(e.replace(/\D/g,"")),t&&e>t&&s.val(e.slice(0,e.length-1))}))}static setPhone(e,t=!1,s=10,i=[2,5]){let a=r.selectElem(e,HTMLElement,!0);a.on("input",(function(e){let r="",n="",o=!1;t?(s=10===s?13:s,r=a.val().replaceAll(/[^0-9+]/g,""),r.includes("+")||(n="+",o=!0)):r=a.val().replace(/\D/g,"");for(let e=0;e<Math.min(r.length,s);e++)t&&n.includes("+")&&"+"==r[e]||(n+=r[e],i.includes(e)&&(n+=" "));o||"+"!==n||(n=""),a.val(n.trimEnd())}))}formatDateTimeWithAMPM(e){let t=e.getHours(),r=e.getMinutes(),s=t>=12?"pm":"am";t%=12,t=t||12,r=r<10?"0"+r:r;return`${e.getDate()} ${["January","February","March","April","May","June","July","August","September","October","November","December"][e.getMonth()]},${e.getFullYear()} by ${t}:${r} ${s}`}static liveVerify(r){let s=new t(r?.rules||r,r?.errorMsgs||{}),i=r?.callback||s.showErrors.bind(s),a=r?.conThrottle||500,n=r?.throttle||300;if("function"!=typeof i)throw new TypeError("callback paratemer needs to be a function");let o=s.debounce((async function(e,t,r,s){2===await this.runRules(this.getDataFromInp(e),r,t)&&this.errors.hasOwnProperty(r)&&delete this.errors[r],s(r,this.rules,this.errors,this)}),n),l=s.debounce((function(e,t){let r="file"===e.type?null:e.value;0==this.required(r,null,t)&&(this.putError(t,"required"),i(t,this.rules,this.errors,this))}),n);for(const t in s.rules)if(s.rules.hasOwnProperty(t)){let r=e(`[name="${t}"]`),n=s.resolveRule(s.rules[t]),h=n.includes("required");if(s.runConrules(t,n,a,i)>-1)continue;h&&r.on("blur focus",(()=>{l(r[0],t)})),r.on("input",(()=>o(r[0],n,t,i)))}}getConrule(e){let t=["any_of","only_any_of"];for(let r=0;r<e.length;r++)if("object"==typeof e[r])for(const s of t)if(e[r].hasOwnProperty(s))return[r,s];return[-1]}debounce(e,t){let r,s,i,a=Date.now(),n=this;return async function(...o){r=Date.now(),i=r-a,clearTimeout(s),s=setTimeout((async()=>{await e.apply(n,o),a=Date.now()}),t-i)}}async#e(e,t,r,s,i,a,n){let o,l=[];for(const e in t)if(t.hasOwnProperty(e)&&(o=await this.verify(this.getDataByKey(e,!0),e,t[e],i),2===o)){if("only_any_of"!=s){l=o,this.deleteErrors(t,r,s);break}l.push(e)}if("only_any_of"===s){let i=this.only_any_of_errs(r,l,t,n,e);1==i?this.deleteErrors(t,r,s):3==i&&delete this.errors[l[0]]}else this.conerrors[r][s].size>0&&(this.errors[e]=this.getUserError(e,s)||this.conerrors[r][s].get(e));a(null,t)}runConrules(t,r,s,i){let[a,n]=this.getConrule(r);if(a>-1){let o="only_any_of"==n?r[a][n].fields:r[a][n],l=this.regConErrors(t,n),h={},u=this.debounce(this.#e,s),c=r[a][n]?.makeInvalidEmpty;for(const r in o)if(o.hasOwnProperty(r)){h[r]=this.resolveRule(o[r]),e(`[name="${r}"]`).on("input",(()=>u(r,h,t,n,l,i,c)))}return a}}deleteErrors(e,t,r){this.conerrors[t][r].clear();for(const t in e)e.hasOwnProperty(t)&&delete this.errors[t]}static getfileSize(e){if(e<1024)return e+" bytes";if(e<1048576){const t=e/1024;return t%1==0?t+" kb":t.toFixed(2)+" kb"}if(e<1073741824){const t=e/1048576;return t%1==0?t+" mb":t.toFixed(2)+" mb"}if(e<1099511627776){const t=e/1073741824;return t%1==0?t+" gb":t.toFixed(2)+" gb"}{const t=e/1099511627776;return t%1==0?t+" TB":t.toFixed(2)+" TB"}}addFunc(e,r,s){if("function"!=typeof e)throw new Error(`${r} does not refer to a function`);if("string"!=typeof r||"string"!=typeof s)throw new TypeError("You must provide ruleName and errorMessage for your function",e);if("function"==typeof t.prototype[r]||"string"==typeof t.errorMessages[r])throw new TypeError("A rule or error message with this name already exists kindly rename your rule.");t.prototype[r]=e,t.errorMessages[r]=s}static extend(e,r=null,s=null){if("function"==typeof e)t.prototype.addFunc(e,r,s);else for(const r in e)e.hasOwnProperty(r)&&t.prototype.addFunc(e[r].callback,r,e[r].msg)}getUserError(e,t){return this.customMessages?.[e]?.[t]||this.customMessages?.[`${e}_${t}`]}getError(e,r){return this.getUserError(e,r)||t.errorMessages?.[r]||t.defaultMsg}getDimensionError(e,r,s={}){let i="dimension";return this.customMessages?.[e]?.[i]?.[r]||this.customMessages?.[`${e}_${i}_${r}`]||t.strReplace(t.errorMessages[`${i}_${r}`],s)}resolveDimensionErrors(e,t,r,s,i,a){this.addErrorConditionally(e,this.getDimensionError(e,t,{givenWidth:s,givenHeight:i,expectedWidth:r[0],expectedHeight:r[1]}),a)}rE(e,r,s){let i=this.getError(e,r);if(s){let e=s;switch(r){case"tillDate":"number"==typeof s&&(s=-s),e=this.formatDateTimeWithAMPM(t.getDate(s));break;case"shouldOld":s instanceof Date&&(e=s.getFullYear());break;case"image":case"fileType":case"inList":case"fileExt":e=s.join(", ")}i=i.replace(`{${r}}`,e)}return i}addError(e,r){return this.errors[e]=r||t.defaultMsg,2}putError(e,r,s=null,i=!0,a=!0){let n;return n=s?t.strReplace(this.getError(e,r),s,a):this.getError(e,r),this.addErrorConditionally(e,n,i)}addErrorConditionally(e,t,r){return!0===r?this.errors[e]=t:this.conerrors[r.inp][r.ruleName].set(e,t),2}getErrors(){return this.errors}static strReplace(e,t,r=!0){for(const s in t)t.hasOwnProperty(s)&&(e=r?e.replace(`{${s}}`,t[s]):e.replace(s,t[s]));return e}addOrRemoveClass(r,s,i=!1){let a=e(`[name="${r}"]`);a.removeClass(t.classes[0]),a.next().filter(`.${t.classes[1]}`)?.remove(),i&&(a.addClass(t.classes[0]),a.after(`<div class="${t.classes[1]}">${s}</div>`))}baseShowErrors(e){this.errors.hasOwnProperty(e)?this.addOrRemoveClass(e,this.errors[e],!0):this.addOrRemoveClass(e)}showErrors(e=null,t){if(e)this.baseShowErrors(e);else for(const e in t)this.baseShowErrors(e)}showConErr(e){for(const t in e)e.hasOwnProperty(t)&&this.baseShowErrors(t)}static async verifyData(e,r=null){let s;e.hasOwnProperty("rules")?s=new t(e.rules,e?.errorMsgs||{},e.data):r instanceof t&&(s=r,s.data=e.data);let i=e?.callback||s.showErrors.bind(s);if(s.data instanceof FormData)for(const e in s.rules)await s.verify(s.data.getAll(e),e,s.resolveRule(s.rules[e]));else if("object"==typeof s.data)for(const e in s.rules)await s.verify(s.data[e],e,s.resolveRule(s.rules[e]));let a=s.isValid();if(!a){if("function"!=typeof i)throw new TypeError("The given callback needs to be a function.");i(null,s.rules,s.errors,s)}return a}isValid(){return 0===Object.keys(this.errors).length}async verify(e,t,r,s=!0,i=!1){return void 0!==e&&0!==Object.keys(e).length||!r.includes("accept")?await this.runRules(e,t,r,s,i):this.accept(null,null,t,s)}async runRules(e,t,r,s=!0,i=!1){let a;i&&(a=[]);for(const n of r){let[r,o]=this.resolveSubRule(n);if("function"!=typeof this[r])throw new Error("There is no rule defined with name "+r+".");if(Array.isArray(e)||e instanceof FileList)for(let n of e){if(a=await this.baseVerifier(r,t,o,n,s),1==a){if(i)continue;return 1}if(i)return 2}else{if(a=await this.baseVerifier(r,t,o,e,s),1==a){if(i)continue;return 1}if(i)return 2}}return i?1:2}async baseVerifier(e,t,r,s,i=!0){if("required"!=e&&"any_of"!=e&&"only_any_of"!=e&&"string"==typeof s&&0==s.trim().length)return 2;try{switch(await this[e](s,r,t,i)){case!1:case 0:return this.addErrorConditionally(t,this.rE(t,e,r),i),1;case 2:return 1}return 2}catch(e){console.error(e)}}resolveRule(e){if("string"==typeof e)return e.split("|");if(Array.isArray(e))return e;if("object"==typeof e)return[e];throw new TypeError(`You need to pass rules as an array or a string. You can only pass a single rule inside an object. ${typeof e} is not allowed as a rule.`)}resolveSubRule(e){let t=e,r=null;if("string"==typeof e)e.includes(":")&&([t,r]=e.split(":"));else{if("object"!=typeof e)throw new TypeError("Inside a rule you can't give another rule as an"+typeof e+" . You can only give a subrule as a string or object.");for(let s in e)t=s,r=e[s]}return[t,r]}getDataFromInp(e,t=!1){return"file"===e.type?t?e.files:e.files?.[0]:e.value}getDataByKey(e,t=!1){let s=r.selectElem(`[name="${e}"]`,HTMLElement);return this.getDataFromInp(s,t)}getData(e,t=!1){return this.data instanceof FormData?t?this.data.getAll(e):this.data.get(e):this.data?!t&&(this.data[e]instanceof FileList||Array.isArray(this.data[e]))?this.data?.[e][0]:this.data[e]:this.getDataByKey(e,t)}checkNumber(e,t){if(e=Number(e),isNaN(e))throw new TypeError(`In ${t} you didn't pass a valid number to validate this rule.`);return e}checkFile(e){return e instanceof File&&"application/octet-stream"!==e.type}accept(e,t,s,i){return r.selectElem(`[name='${s}']`,HTMLInputElement,!0).prop("checked")?1:this.addErrorConditionally(s,this.rE(s,"accept",t),i)}async any_of(e,t,r){let s=this.regConErrors(r,"any_of");for(const e in t)if(t.hasOwnProperty(e)&&2==await this.verify(this.getData(e,!0),e,this.resolveRule(t[e]),s))return 1;return this.addError(r,this.getUserError(r,"any_of")||this.conerrors[r].any_of.get(r)),2}async only_any_of(e,t,r){let s,i=t?.fields||t,a=this.regConErrors(r,"only_any_of"),n=[];for(const e in i)i.hasOwnProperty(e)&&(s=await this.verify(this.getData(e,!0),e,this.resolveRule(i[e]),a),2==s&&n.push(e));return this.only_any_of_errs(r,n,i,t?.makeInvalidEmpty)}only_any_of_errs(e,r,s,i=!1,a=!1){let n=r.length,o="only_any_of";if(i&&1===n)for(const i in s)if(s.hasOwnProperty(i)){if(i==r[0])continue;if(this.required(this.getData(i),null,i)&&(this.addError(i,this.getUserError(e,o)?.makeInvalidEmpty||t.errorMessages.makeInvalidEmpty),a))return 3}return 1===n?1:a?this.addError(a,this.getUserError(a,o)?this.getConErr(a,o,n):this.conerrors[e][o].get(a)):this.addError(e,this.getConErr(e,o,n))}getConErr(e,r,s){return 3===s?this.getUserError(e,r)?.makeInvalidEmpty||t.errorMessages.makeInvalidEmpty:this.getUserError(e,r)?.[s>1?"matchMultiple":"matchNone"]||this.conerrors[e][r].get(e)||t.errorMessages.makeInvalidEmpty}async any_of_rules(e,t,r){let s,i=this.regConErrors(r,"any_of_rules");for(let a=0;a<t.length&&(s=await this.verify(e,r,this.resolveRule(t[a]),i),2!==s);a++);return 1==s&&this.addError(r,this.getUserError(r,"any_of_rules")||this.conerrors[r].any_of_rules.get(r)),s>1?1:2}alpha(e,t){return t?/^[\p{L}\s]+$/u.test(e):/^[\p{L}]+$/u.test(e)}alphaNumeric(e,t){return t?/^[\p{L}\p{N}\s]+$/u.test(e):/^[\p{L}\p{N}]+$/u.test(e)}lowerCase(e,t){return t?/^[\p{Lowercase}\s]+$/u.test(e):/^[\p{Lowercase}]+$/u.test(e)}upperCase(e,t){return t?/^[\p{Uppercase}\s]+$/u.test(e):/^[\p{Uppercase}]+$/u.test(e)}detectMultipleSpaces(e,t,r,s){let i=e.replace(/\s+/g," ")===e;return i||this.putError(r,ruleName,null,s)}email(e){return/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(e)}hasLowerCase(e){return/[\p{Lowercase}]/u.test(e)}hasUpperCase(e){return/[\p{Uppercase}]/u.test(e)}hasSpecial(e){return t.REG_SPECIAL.test(e)}noSpace(e){return!/\s+/g.test(e)}noSpecial(e){return!t.REG_SPECIAL.test(e)}max(e,t){return!(e.trim().length>t)}min(e,t){return!(e.trim().length<t)}same(e,t){return e===this.getData(t)}space(e,t,r,s){let i=/\s+/g.test(e);return i&&t?this.detectMultipleSpaces(e,null,r,s):i}password(e,r,s,i){let a=!1;if(this.hasLowerCase(e)?this.hasUpperCase(e)?this.hasDigit(e)?this.hasSpecial(e)?this.min(e,r||8)||(a="min"):a="hasSpecial":a="hasDigit":a="hasUpperCase":a="hasLowerCase",a){let e=this.getUserError(s,a)||this.getUserError(s,"password")||t.strReplace(t.errorMessages[a],{"{min}":r||8,field:"password"},!1);return this.addErrorConditionally(s,e,i)}return 1}hasDigit(e){return/[0-9]/.test(e)}minnumb(e,t){return!(e>t)}maxnumb(e,t){return!(e<t)}numb(e){return/^[0-9]+$/.test(e)}numb_space(e,t,r,s){e=e.trim();let i=/^[0-9 ]+$/.test(e);return i&&t&&this.detectMultipleSpaces(e,null,r,s),i}range(e,t,r,s){return e<t[0]||e>t[1]?this.putError(r,"range",{num1:t[0],num2:t[1]},s):1}shouldOld(e,t,r){t=this.checkNumber(t,"shouldrule");let s=this.getFormatedDate(e,r),i=new Date,a=i.getFullYear()-s.getFullYear();return a===t?s.getMonth()==i.getMonth()?s.getDate()<=i.getDate():s.getMonth()<i.getMonth():a>=t}tillDate(e,r,s){return"number"==typeof r&&(r=-r),r=t.getDate(r),!(this.getFormatedDate(e,s).getTime()>r.getTime())}getFormatedDate(e,t){if(this.dateFormat[t]){let r=[...this.dateFormat[t]];r[1]--;let s=e.indexOf("T");if(s>-1){let t=e.slice(s+1).split(":").map(Number);r.push(...t)}return new Date(...r)}return new Date(e)}dateAll(e,t,r){return this.date(e,"YYYY-DD-MM",r)||this.date(e,"YYYY/DD/MM",r)||this.date(e,"MM/DD/YYYY",r)||this.date(e,"DD/MM/YYYY",r)||this.date(e,"YYYY-MM-DD",r)}date(e,t,r){let s="YYYY-DD-MM";t&&(s=t);let i=/^\d{4}-\d{1,2}-\d{1,2}$/,a=2,n=1,o=0;if("YYYY-MM-DD"==s)a=1,n=2;else if("YYYY/DD/MM"==s)i=/^\d{4}\/\d{1,2}\/\d{1,2}$/;else if("MM/DD/YYYY"==s||"DD/MM/YYYY"==s){i=/^\d{1,2}\/\d{1,2}\/\d{4}$/;let e="DD/MM/YYYY"==s;a=e?1:0,n=e?0:1,o=2}if(!i.test(e))return!1;let l=e.includes("-")?"-":"/",h=e.split(l).map(Number),u=h[n],c=h[a],d=h[o];if(d<1e3||d>3e3||c<1||c>12||u<1)return!1;const f=[31,28,31,30,31,30,31,31,30,31,30,31];return(d%4==0&&d%100!=0||d%400==0)&&(f[1]=29),u<=f[c-1]?(this.dateFormat[r]=[d,c,u],!0):void 0}dateTime(e,t,r){let s,i=e.split(" ");if(s=t?this.date(i?.[0],t,r):this.dateAll(i?.[0],null,r),s){let e=i?.[1]?.split(":")?.map(Number);if(3!==e?.length||e[0]>23||e[0]<0||e[1]>59||e[1]<0||e[2]>59||e[2]<0)return!1;if(/^\d{1,2}:\d{1,2}:\d{1,2}$/.test(i?.[1]))return this.dateFormat[r].push(...e),!0}return!1}fileSize(e,r,s,i){return r=this.checkNumber(r,"fileSize"),e instanceof File&&e.size>r?this.putError(s,"fileSize",{fileSize:t.getfileSize(r),fileSize2:t.getfileSize(e.size)},i):1}fileType(e,t){return!this.checkFile(e)||t.includes(e.type)}fileExt(e,t){return this.checkFile(e)?t.includes(e.name.split(".").pop()):1}async notRule(e,t,r){return 1!==await this.verify(e,r,this.resolveRule(t),this.regConErrors(r,"notRule"),!0)?this.addError(r,this.getUserError(r,"notRule")):1}dimension(e,r,s,i){return new Promise((a=>{if((r?.mimeTypes||t.imgMimeTypes).includes(e.type)){const t=new FileReader;t.onload=e=>{let t=new Image;t.src=e.target.result,t.onload=()=>{let e=t.width,n=t.height;if(r.hasOwnProperty("height")||r.hasOwnProperty("width"))r?.height&&r.height!==n&&(this.addErrorConditionally(s,this.getDimensionError(s,"height",{height:n}),i),a(2)),r?.width&&r.width!==e&&(this.addErrorConditionally(s,this.getDimensionError(s,"width",{width:e}),i),a(2));else if(r.hasOwnProperty("equal"))r.equal[0]===e&&r.equal[1]===n||(this.resolveDimensionErrors(s,"equal",r.equal,e,n,i),a(2));else if(r.hasOwnProperty("smallest")||r.hasOwnProperty("highest"))r?.smallest&&(e<r.smallest[0]||n<r.smallest[1])&&(this.resolveDimensionErrors(s,"smallest",r.smallest,e,n,i),a(2)),r?.highest&&(e>r.highest[0]||n>r.highest[1])&&(this.resolveDimensionErrors(s,"highest",r.highest,e,n,i),a(2));else if(r.hasOwnProperty("square"))0===r.square?e!==n&&(this.addErrorConditionally(s,this.getDimensionError(s,"square",{}),i),a(2)):e===r.square&&n===r.square||(this.resolveDimensionErrors(s,"square_size",[r.square,r.square],e,n,i),a(2));else if(r.hasOwnProperty("ratio")){let t=e/n,o=r.ratio;if("string"==typeof o){let[e,t]=o.split(":").map(Number);if(o=e/t,isNaN(o))throw new TypeError(`The given aspectRatio ${r.ratio} is invalid the format should be like this 16:9, 4.8089:1.7823 etc.`)}Math.abs(t-o)<(r?.difference??.1)||(this.addErrorConditionally(s,this.getDimensionError(s,"aspectRatio",{aspectRatio:r.ratio}),i),a(2))}a(1)}},t.readAsDataURL(e)}else a(this.image(e,r?.mimeTypes,s,i))}))}image(e,r,s,i){if(this.checkFile(e)){let a=t.imgMimeTypes;if(r&&(a=r),!a.includes(e.type))return this.addErrorConditionally(s,this.rE(s,"image",a),i)}return 1}required(e,t,s){if("string"!=typeof e){let e=r.selectElem(`[name="${s}"`,HTMLElement);return e?.files?.length>0?1:0}return e.trim().length>0?1:0}inList(e,t){return t.includes(e)}url(e,t,r,s){return t?/^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i.test(e)?1:this.putError(r,"url_ftp",null,s):/^https?:\/\/[^\s/$.?#].[^\s]*$/i.test(e)}zipCode(e){return/^\d{5}(?:-\d{4})?$/.test(e)}json(e,t=null){try{let r=JSON.parse(e);return t?"object"==typeof r&&null!==r:1}catch(e){return 0}}ipv4(e){return/^(\d{1,3}\.){3}\d{1,3}$/.test(e)}ipv6(e){return/^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^::$|^::1$/.test(e)}isbnCheckSum(e){let t,r=e.split("");for(let e=0;e<r.length;e++)r[e]=(10-e)*r[e];return t=(11-r.reduce(((e,t)=>e+t),0)%11)%11,t<10?t:"X"}isbn10(e){return!!/^\d{9}[0-9X]$/.test(e)&&this.isbnCheckSum(e.slice(0,-1))==e.slice(-1)}calculateChecksum(e){let t=e.split("").map(Number);return{checkDigit:t.pop(),oddSum:t.filter(((e,t)=>t%2==0)).reduce(((e,t)=>e+t),0),evenSum:t.filter(((e,t)=>t%2==1)).reduce(((e,t)=>e+t),0)}}barcode(e){if(e.length<8||e.length>18||8!=e.length&&12!=e.length&&13!=e.length&&14!=e.length&&18!=e.length)return!1;var t=Number(e.slice(-1));if(isNaN(t))return!1;for(var r=e.slice(0,-1).split("").reverse(),s=0,i=0,a=0;a<r.length;a++){if(isNaN(r[a]))return!1;a%2==0?s+=3*Number(r[a]):i+=Number(r[a])}return(10-(i+s)%10)%10==t}upca(e){if(!/^\d+$/.test(e))return!1;if(12===e.length){let{checkDigit:t,oddSum:r,evenSum:s}=this.calculateChecksum(e);return(3*r+s+t)%10==0}return!1}eanCheckSum(e){let t=7===e.length?[3,1]:[1,3],r=e.split(""),s=0,i=0;for(;i<r.length;i++)s+=Number(r[i])*t[i%2];return(10-s%10)%10}ean(e){return!!/^(?:\d{8}|\d{13})$/.test(e)&&this.eanCheckSum(e.slice(0,-1))===Number(e.slice(-1))}regex(e,t){return t.test(e)}notRegex(e,t){return!t.test(e)}}class r{static readBlobAsBase64(e,t=1){return new Promise(((s,i)=>{const a=new FileReader;t=1024*t*1024;let n=0;const o=[];function l(){const r=e.slice(n,n+t);a.readAsDataURL(r),n+=r.size}a.onload=function(t){if(0===o.length?o.push(t.target.result):o.push(t.target.result.split(",")[1]),n<e.size)l();else{const t=o.join("");s({name:e.name,filesize:e.size,type:e.type,lastModified:e.lastModified,base64:t,base64size:r.base64size(t)})}},a.onerror=function(){i(a.error)},l()}))}static base64size(e){const t=e.includes(",")?e.split(",")[1]:e,r=t.length,s=3*r/4;let i=0;for(;"="==t[r-i-1];)i++;return s-3*i/4}static#t(e,t){if(null!==t.inputs)if(Array.isArray(t.inputs))for(const s of t.inputs)e=r.#r(e,s,t.overwrite);else{if("object"!=typeof t.inputs)throw new TypeError(`Object, FormData and arrays are only allowed ${typeof t.inputs} is not allowed.`);e=r.#r(e,t.inputs,t.overwrite)}return e}static#r(e,t,s){if(t instanceof FormData)for(const i of new Set(t.keys())){let a=t.getAll(i);e=r.#s(e,i,a,s)}else for(const i of Object.keys(t))e=r.#s(e,i,t[i],s);return e}static#s(e,t,s,i){let a=!("overwritenone"===i||"overwritefiles"===i);if(e=r.overWritedata(e,t,i),"object"==typeof s||Array.isArray(s)||s instanceof FileList)for(const r of s)!e.has(t)||s instanceof File||!a||e.delete(t),e.append(t,r);else e.append(t,s);return e}static selectElem(t,r=HTMLFormElement,s=!1){let i=null;if(t instanceof r?i=t:"string"==typeof t?i=s?e(t):document.querySelector(t):t?.[0]instanceof r&&(i=s?t:t[0]),!(i instanceof r||i?.[0]instanceof r))throw new TypeError(`No element in dom exists with this ${t} selector.`);return i}static fileInputs(e){return r.selectElem(e).querySelectorAll('input[type="file"]')}static async selectFiles(e,t=!1){let s={},i=r.fileInputs(e);if(i.length>0)for(const e of i)if(e.files.length>0){let i=e.getAttribute("name");try{if(s[i]=e.files,t){let e=[];for(const t in s){for(const i in s[t])e.push(await r.readBlobAsBase64(i));s[t]=e}}}catch(e){console.error(e)}}return s}static quickSubmit(e){r.selectElem(e.form).onsubmit=async t=>{t.preventDefault(),await r.justSubmit(e)}}static overWritedata(e,t,r){return"overwritenone"!==r&&("overwriteall"===r&&e.has(t)?e.delete(t):"overwritefiles"===r&&e.has(t)?e.get(t)instanceof File&&e.delete(t):"overwritebutnotfiles"===r&&e.has(t)&&(e.get(t)instanceof File||e.delete(t))),e}static async justSubmit(s){(s={overwrite:"overwriteAll",inputs:null,...s}).overwrite=s.overwrite.toLowerCase();let i,a={type:"POST",...s.ajaxSettings},n="json"===a?.dataType?.toLowerCase();if(s.form instanceof HTMLFormElement||"string"==typeof s.form){let e=r.selectElem(s.form);i=new FormData(e)}else"object"==typeof s.form&&(i=s.form);if(i instanceof FormData&&(s.hasOwnProperty("resetKeys")&&s.resetKeys.forEach((e=>i.delete(e))),i=r.#t(i,s)),s.hasOwnProperty("validate")||s.hasOwnProperty("rules"))if(s.validate instanceof t){if(!await t.verifyData({data:i},s.validate))return!1}else{if(s.hasOwnProperty("validate")&&!await t.verifyData({data:i,...s.validate}))return!1;if(!await t.verifyData({data:i,rules:s.rules}))return!1}if(n&&(i=await r.objectToJson(i,s.overwrite)),a.hasOwnProperty("contentType")&&a.hasOwnProperty("processData")||(n?(a.contentType="application/json",a.processData=!1):i instanceof FormData&&(a.contentType=!1,a.processData=!1)),a.data=i,!a.hasOwnProperty("success")&&s.hasOwnProperty("responseElem")){let t,r=!1;"string"==typeof s.responseElem?t=e(s.responseElem):(t=e(s.responseElem.elem),r=s.responseElem.key),a.success=e=>{t.css("display","block"),r?t.html(e[r]):t.html(e)}}e.ajax(a)}static inJson(e,t=!1){if(t){let t={};return e.forEach((e=>{t[e.name]=e.value})),JSON.stringify(t)}return e}static async#i(e,t,s,i){const a=[],n=[];for(const e of s)e instanceof File?a.push(await r.readBlobAsBase64(e)):n.push(e);return a.length>0&&(e[t]=a),n.length>0&&a.length>0?i&&n.length>1?e[`${t}_text`]=n:e[`${t}_text`]=n[n.length-1]:n.length>0&&(e[t]=i?n:n[n.length-1]),e}static async objectToJson(e,t){let s={};const i="overwritenone"===t||"overwritefiles"===t;if(e instanceof FormData)for(let t of new Set(e.keys())){let a=e.getAll(t);a.length>1?s=await r.#i(s,t,a,i):a[0]instanceof File?s[t]=await r.readBlobAsBase64(a[0]):s[t]=a[0]}else for(let t in e)e[t]instanceof FileList||Array.isArray(e[t])?s=await r.#i(s,t,inputs,i):e[t]instanceof File?s[t]=await r.readBlobAsBase64(e[t]):s[t]=e[t];return JSON.stringify(s)}}return[t,r]}));