UNPKG

js-formdata-validator

Version:

JS Form Validator is a simple form data validation library for JavaScript. It provides a set of base rules for checking the type and value of various inputs, and allows you to define custom rules as well.

2 lines (1 loc) 10.1 kB
(function(d,n){typeof exports=="object"&&typeof module<"u"?n(exports):typeof define=="function"&&define.amd?define(["exports"],n):(d=typeof globalThis<"u"?globalThis:d||self,n(d["js-formdata-validator"]={}))})(this,function(d){"use strict";var E=Object.defineProperty;var v=(d,n,s)=>n in d?E(d,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):d[n]=s;var l=(d,n,s)=>(v(d,typeof n!="symbol"?n+"":n,s),s);const n={required:"The {field} cannot be empty",array:"The {field} must be instance of Array",integer:"The {field} must be integer",numeric:"The {field} must be numeric",string:"The {field} must be string",boolean:"The {field} must be a boolean",allowed:"The {field} must be one of the following: {args}",email:"The {field} is not a valid email address",min:"The {field} has minimum of {minSize} but it got value {value}",max:"The {field} has maximum of {maxSize} but it got value {value}",ipv4:"The {field} must be an IPv4 address",ipv6:"The {field} must be an IPv6 address",accepted:"The {field} must be accepted",declined:"The {field} must be declined"},s=({fieldName:a,rule:e,customValidatorErrorMessage:r={}})=>({...n,...r})[e].replace("{field}",a),m={required({value:a,fieldName:e,customValidatorErrorMessage:r}){if(a===void 0||a===""||a===null)return s({fieldName:e,rule:"required",customValidatorErrorMessage:r})},array({value:a,fieldName:e,customValidatorErrorMessage:r}){if(!(a instanceof Array))return s({fieldName:e,rule:"array",customValidatorErrorMessage:r})},integer({value:a,fieldName:e,customValidatorErrorMessage:r}){if(!Number.isInteger(a))return s({fieldName:e,rule:"integer",customValidatorErrorMessage:r})},numeric({value:a,fieldName:e,customValidatorErrorMessage:r}){if(typeof a!="number")return s({fieldName:e,rule:"numeric",customValidatorErrorMessage:r})},string({value:a,fieldName:e,customValidatorErrorMessage:r}){if(typeof a!="string")return s({fieldName:e,rule:"string",customValidatorErrorMessage:r})},boolean({value:a,fieldName:e,customValidatorErrorMessage:r}){if(typeof a!="boolean")return s({fieldName:e,rule:"boolean",customValidatorErrorMessage:r})},allowed({value:a,fieldName:e,customValidatorErrorMessage:r},...t){if(!t.includes(a))return s({fieldName:e,rule:"allowed",customValidatorErrorMessage:r}).replace("{args}",t.join(", "))},email({value:a,fieldName:e,customValidatorErrorMessage:r}){if(!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(a))return s({fieldName:e,rule:"email",customValidatorErrorMessage:r})},min({value:a,fieldName:e,customValidatorErrorMessage:r},t){if(t===void 0)return"Please define the min value. Example min:26";if(Number.isFinite(Number(a))){const i=parseInt(a);if(i<t)return s({fieldName:e,rule:"min",customValidatorErrorMessage:r}).replace("{minSize}",t.toString()).replace("{value}",i.toString())}else if(typeof a=="string"){const i=a.length;if(i<t)return s({fieldName:e,rule:"min",customValidatorErrorMessage:r}).replace("{minSize}",t.toString()).replace("{value}",i.toString())}},max({value:a,fieldName:e,customValidatorErrorMessage:r},t){if(t===void 0)return"Please define the max value. Example: max:26";if(Number.isFinite(Number(a))){const i=parseInt(a);if(i>t)return s({fieldName:e,rule:"max",customValidatorErrorMessage:r}).replace("{maxSize}",t.toString()).replace("{value}",i.toString())}else if(typeof a=="string"){const i=a.length;if(i>t)return s({fieldName:e,rule:"max",customValidatorErrorMessage:r}).replace("{maxSize}",t.toString()).replace("{value}",i.toString())}},ipv4({value:a,fieldName:e,customValidatorErrorMessage:r}){const t="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}";if(!new RegExp(`^${t}$`).test(a&&a.toString()))return s({fieldName:e,rule:"ipv4",customValidatorErrorMessage:r})},ipv6({value:a,fieldName:e,customValidatorErrorMessage:r}){const t="((([0-9a-fA-F]){1,4}):){7}([0-9a-fA-F]){1,4}";if(!new RegExp(`^${t}$`).test(a&&a.toString()))return s({fieldName:e,rule:"ipv6",customValidatorErrorMessage:r})},accepted({value:a,fieldName:e,customValidatorErrorMessage:r}){if(!["yes","on",1,!0].includes(a))return s({fieldName:e,rule:"accepted",customValidatorErrorMessage:r})},declined({value:a,fieldName:e,customValidatorErrorMessage:r}){if(!["no","off",0,!1].includes(a))return s({fieldName:e,rule:"declined",customValidatorErrorMessage:r})}};class g{constructor(){l(this,"errorMessage");l(this,"errorBag",{})}add(e,r){this.errorBag[e]?this.errorBag[e].push(r):this.errorBag[e]=[r]}clearErrorBag(){this.errorBag={}}getErrorBag(){return this.errorBag}setFieldErrors(e,r){this.errorBag[e]=r}setErrorMessage(e){this.errorMessage=e}getErrorMessage(){return this.errorMessage||this.defaultErrorMessage()}defaultErrorMessage(){return`${Object.keys(this.errorBag).length} error occured`}hasErrors(){return Object.keys(this.errorBag).length>0}}class f{constructor({formData:e,customRules:r,rules:t,stopOnFirstFailure:i}={}){l(this,"formData");l(this,"rules");l(this,"validatorError");l(this,"validator");l(this,"stopOnFirstFailure");l(this,"customFieldNames",{});l(this,"customValidatorErrorMessage",{});this.formData=e??{},this.rules=t??{},this.validatorError=new g,this.stopOnFirstFailure=i??!1,this.mergeCustomRules(r)}mergeCustomRules(e){return this.setValidator({...m,...e}),this}async validate(){if(this.stopOnFirstFailure)for(const e in this.rules){if(this.validatorError.hasErrors())break;await this.validateField({field:e,fieldRules:this.rules[e]})}else{const e=Object.entries(this.rules).map(([r,t])=>this.validateField({field:r,fieldRules:t}));await Promise.all(e)}return this}async validateField({field:e,fieldRules:r}){const t=e.split(".");t.includes("*")?await this.validateArrayObjects(e,t,r):await this.validateFieldValue(e,t,r)}async validateArrayObjects(e,r,t){const i=r.indexOf("*"),u=this.formData[r[i-1]];for(let o=0;o<u.length;o++)if(!t.every(h=>{typeof this.getValidatorResult(e,u[o],h)>"u"})){const h=e.replace("*",`${o}`);await this.validateField({field:h,fieldRules:t})}}async validateFieldValue(e,r,t){let i=this.formData;for(const u of r)i=i[u];if(this.stopOnFirstFailure)for(const u of t){const o=await this.getValidatorResult(e,i,u);if(o){this.validatorError.add(e,o);break}}else(await Promise.all(t.map(o=>typeof this.getValidatorResult(e,i,o)=="object"?this.getValidatorResult(e,i,o):Promise.resolve(this.getValidatorResult(e,i,o))))).forEach(o=>{o&&this.validatorError.add(e,o)})}getValidatorResult(e,r,t){let i;switch(typeof t){case"string":{i=this.handleStringRule(e,t);break}case"function":{i=t(r,this.formData);break}}return i}handleStringRule(e,r){const[t,i]=this.parseRule(r);if(!(t in this.validator)||e.includes("*"))return;const u=e.split(".").reduce((c,h)=>c[h],this.formData);let o=e;return Object.keys(this.customFieldNames).includes(e)&&(o=this.customFieldNames[o]),this.validator[t]({value:u,formdata:this.formData,fieldName:o,customValidatorErrorMessage:this.customValidatorErrorMessage},...i)}parseRule(e){const[r,t]=e.split(":"),i=t?t.split(",").map(u=>u.trim()):[];return[r,i]}getErrorBag(){return this.validatorError.getErrorBag()}getErrorMessage(){return this.validatorError.getErrorMessage()}setErrorMessage(e){return this.validatorError.setErrorMessage(e)}getError(e){var r;return(r=this.validatorError.getErrorBag()[e])==null?void 0:r[0]}getFailedFields(){return Object.keys(this.getErrorBag())}pass(){return Object.keys(this.getErrorBag()).length===0}fail(){return!this.pass()}clearErrors(){return this.validatorError.clearErrorBag(),this}getFormData(){return this.formData}setFormData(e){return this.formData=e,this}setFieldErrors(e,r){this.validatorError.setFieldErrors(e,r)}setFormKeyValue(e,r){this.formData[e]=r}getValidator(){return this.validator}setValidator(e){return this.validator=e,this}getRules(){return this.rules}setRules(e){return this.rules=e,this}setCustomFieldName(e){this.customFieldNames=e}getCustomFieldName(){return this.customFieldNames}setCustomValidatorErrorMessage(e){this.customValidatorErrorMessage=e}getCustomValidatorErrorMessage(){return this.customValidatorErrorMessage}}class p{constructor(){l(this,"fieldName");l(this,"fieldValue");l(this,"fieldRules");l(this,"validatorError");l(this,"validator");l(this,"formData");l(this,"customFieldName");l(this,"customValidatorErrorMessage",{});this.fieldName="",this.fieldRules=[],this.fieldValue=null,this.validatorError=new g,this.validator=m,this.formData={}}setCustomRules(e){this.mergeCustomRules(e)}setFieldName(e){this.fieldName=e}setFormData(e){this.formData=e}getFormData(){return this.formData}getFieldName(){return this.fieldName}setFieldRules(e){this.fieldRules=e}getFieldRules(){return this.fieldRules}setFieldValue(e){this.fieldValue=e}getFieldValue(){return this.fieldValue}async validate(){this.validatorError.clearErrorBag(),(await Promise.all(this.fieldRules.map(r=>typeof this.getValidatorResult(r)=="object"?this.getValidatorResult(r):Promise.resolve(this.getValidatorResult(r))))).forEach(r=>{r&&this.validatorError.add(this.fieldName,r)})}async getValidatorResult(e){let r;switch(typeof e){case"string":{r=this.handleStringRule(e);break}case"function":{r=e(this.fieldValue,this.formData);break}}return r}handleStringRule(e){const[r,t]=this.parseRule(e);return this.validator[r]({value:this.fieldValue,fieldName:this.customFieldName||this.fieldName,formdata:this.formData,customValidatorErrorMessage:this.customValidatorErrorMessage},...t)}parseRule(e){const[r,t]=e.split(":"),i=t?t.split(",").map(u=>u.trim()):[];return[r,i]}pass(){return!this.validatorError.hasErrors()}fail(){return!this.pass()}getErrorBag(){return this.validatorError.getErrorBag()[this.fieldName]}mergeCustomRules(e){return this.setValidator({...m,...e}),this}setValidator(e){return this.validator=e,this}setCustomFieldName(e){this.customFieldName=e}getCustomFieldName(){return this.customFieldName}setCustomValidatorErrorMessage(e){this.customValidatorErrorMessage=e}getCustomValidatorErrorMessage(){return this.customValidatorErrorMessage}}d.FieldValidator=p,d.Validator=f,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"})});