formoose
Version:
Schema-based run time validation engine, made to integrate back and front-end validations using Mongoose like schemas.
3 lines (2 loc) • 7.66 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ReactHookForm={},e.React)}(this,(function(e,t){"use strict";class o extends Error{constructor(e,t,n,a){super(e),Object.setPrototypeOf(this,o.prototype),this.name="FormooseError",this.message=e||"Unxpected validation error detected by Formoose.",this.field=t,this.translatedMessageKey=n,this.translatedMessageInterpolators=a}}class n{static throw(e,t,n,a={}){throw new o(e,t,n,a)}}const a=(e,t)=>{let o="";return e.map((e=>(!Object.prototype.hasOwnProperty.call(t,e)&&(o=`${e} not found on Schema.`),o))),""!==o&&n.throw(o),""===o};var r;function l(t,o){return"string"!=typeof t&&n.throw(`String expected, type sent: ${typeof t} - on field: ${o}`,o,e.ErrorCodes["alphabetical-chars-only"],{fieldName:o,fieldValue:t}),!0}function i(t,o){return Array.isArray(t)||n.throw(`Array expected, type sent: ${typeof t} - on field: ${o}`,o,e.ErrorCodes["is-not-an-array"],{fieldName:o,fieldValue:t}),!0}function s(t,o){return(null==t||""===t||t.length<1)&&n.throw(`Required field "${o}" is empty, sent type '${typeof t}' with value: '${t}' - on field: ${o}`,o,e.ErrorCodes["is-empty"],{fieldName:o,fieldValue:t}),!0}function d(t,o){return"number"!=typeof t&&n.throw(`Number expected, type sent: ${typeof t} - on field: ${o}`,o,e.ErrorCodes["is-not-a-number"],{fieldName:o,fieldValue:t}),!0}function u(t,o){return"boolean"!=typeof t&&n.throw(`Expected type boolean, sent '${typeof t}' - on field: ${o}`,o,e.ErrorCodes["is-not-a-boolean"],{fieldName:o,fieldValue:t}),!0}function c(t,o,a){const{validate:r}=o;if(!(null==r?void 0:r.validator(t))){const o=`Custom Validation failed on field: ${a}`;n.throw((null==r?void 0:r.message)||o,a,(null==r?void 0:r.message)||e.ErrorCodes["failed-custom-validate"],{fieldName:a,fieldValue:t})}return!0}function m(t,o,a){return Object.values(o).indexOf(t)>-1||n.throw(`The value '${t}' isn't listed in the possible enumerable list '${JSON.stringify(o)}' - on field: ${a}`,a,e.ErrorCodes["does-not-match-enum"],{fieldName:a,fieldValue:t}),!0}function f(t,o,a){const r=String(t);return l(t,a)&&r.length>o&&n.throw(`String exceed the size of ${o} characters with ${r.length} - on field: ${a}`,a,e.ErrorCodes["chars-limit-exceeded"],{fieldValue:t,size:o,length:t.length,fieldName:a}),!0}function h(t,o,a){const r=String(t);return l(t,a)&&r.length<o&&n.throw(`String with length of ${r.length}, expected at least ${o} characters - on field: ${a}`,a,e.ErrorCodes["chars-lenght-is-too-short"],{fieldValue:t,size:o,length:t.length,fieldName:a}),!0}e.ErrorCodes=void 0,(r=e.ErrorCodes||(e.ErrorCodes={}))["alphabetical-chars-only"]="alphabetical-chars-only",r["is-not-a-boolean"]="is-not-a-boolean",r["is-empty"]="is-empty",r["is-not-a-number"]="is-not-a-number",r["does-not-match-enum"]="does-not-match-enum",r["chars-limit-exceeded"]="chars-limit-exceeded",r["chars-lenght-is-too-short"]="chars-lenght-is-too-short",r["is-not-an-array"]="is-not-an-array",r["failed-custom-validate"]="failed-custom-validate";const p=e=>{const t={Array:i,Boolean:u,Number:d,String:l,default:()=>null};return t[e]||t.default},g=e=>{const{fieldValue:t,schemaItem:o,fieldName:n}=e;p(o.type)(t,n)},v=e=>{const{fieldValue:t,schemaItem:o,fieldName:n}=e;(null==o?void 0:o.required)&&s(t,n)},y=e=>{const{fieldValue:t,schemaItem:o,fieldName:n}=e;(null==o?void 0:o.min)&&h(t,o.min,n)},b=e=>{const{fieldValue:t,schemaItem:o,fieldName:n}=e;(null==o?void 0:o.max)&&f(t,o.max,n)},E=e=>{const{fieldValue:t,schemaItem:o,fieldName:n}=e;(null==o?void 0:o.validate)&&c(t,o,n)},w=e=>{const{fieldValue:t,schemaItem:o,fieldName:n}=e;(null==o?void 0:o.enum)&&m(t,o.enum,n)},V=e=>{const{required:t}=e.schemaItem,{fieldValue:o}=e;if(!t&&(void 0===o||""===o||null===o))return null;for(const t in e.schemaItem)Object.prototype.hasOwnProperty.call(null==e?void 0:e.schemaItem,t)&&("type"===t&&g(e),"required"===t&&v(e),"min"===t&&y(e),"max"===t&&b(e),"validate"===t&&E(e),"enum"===t&&w(e));return!0},F=(e,t,o)=>new Promise((n=>{a(t,o);for(let n=0;n<t.length;n++)V({fieldName:t[n],schemaItem:o[t[n]],fieldValue:e[t[n]]});n(!0)}));function C(e,t){e((e=>({...e,[t]:{...e[t],error:null,message:null}})))}function N(e){const t={};return Object.keys(e).forEach((o=>{t[o]={error:null,message:null,value:e[o]}})),t}function x(e,t,o){e((e=>({...e,[t]:{...e[t],message:o}})))}function S(e,t,o,n){e((e=>({...e,[t]:{...e[t],error:o,message:n(null==o?void 0:o.translatedMessageKey,null==o?void 0:o.translatedMessageInterpolators)}})))}function O(e,t,o){e((e=>({...e,[t]:{...e[t],value:o}})))}function $(e,t,o){const{target:n}=e,{type:a}=n;let r=null;switch(a){case"radio":default:r=n.value;break;case"checkbox":r=n.checked}O(o,t,r)}function k(e,t){return{[t]:e[t].value}}function j(e,t,o,n){return new Promise(((a,r)=>{const l=Object.assign({},t),i=e=>(Object.assign(l,e(l)),l),s=Object.keys(t).map((o=>F(k(t,o),[o],e).then((()=>{C(i,o)})).catch((e=>{throw S(i,o,e,n),e}))));Promise.all(s).then((()=>{o(l),a(!0)})).catch((e=>{o(l),r({formData:l,message:"Invalid Form",result:!1})}))}))}const I=(e,t,o,n,a)=>new Promise((r=>{F(k(o,e),[e],t).then((()=>{C(n,e),r(!0)})).catch((t=>{S(n,e,t,a),r(!1)}))}));function M(e,t){var o;return null===(o=t[e])||void 0===o?void 0:o.max}function T(e,t){const o={};Object.keys(t).map((e=>{o[e]={value:t[e]}})),Object.assign(e,o)}function A(e,t=null,o=!1){const n={};return Object.keys(e).map((t=>{const a=""!==e[t].value&&void 0!==e[t].value;(o||a)&&(n[t]=e[t].value)})),t&&t.forEach((e=>{delete n[e]})),n}const P=e=>{const t={};return Object.keys(e).map((e=>t[e]={error:void 0,message:void 0,value:""})),t};var q;e.SupportedTypesEnum=void 0,(q=e.SupportedTypesEnum||(e.SupportedTypesEnum={}))[q.Array=0]="Array",q[q.Boolean=1]="Boolean",q[q.Number=2]="Number",q[q.String=3]="String";let B=null;const L=e=>{var t;return"string"==typeof e?e:null===(t=null==e?void 0:e.target)||void 0===t?void 0:t.name};e.CustomValidate=E,e.EnsureSchema=V,e.EnumChecker=w,e.ErrorHandler=n,e.Formoose=class{constructor(){throw new Error("Instancing Formoose Class is deperacted. Please use the new hook useFormoose.")}},e.FormooseError=o,e.MaxLengthChecker=b,e.MinLengthChecker=y,e.RequiredChecker=v,e.TypeChecker=g,e.Validate=F,e.checkIfBelongsToSchema=a,e.cleanError=C,e.convertModelToForm=N,e.getMaxLength=M,e.getModel=k,e.getSimpleObject=A,e.getTypeValidator=p,e.handleFieldChange=$,e.isArray=i,e.isBoolean=u,e.isEmpty=s,e.isNumber=d,e.isString=l,e.matchEnum=m,e.matchValidate=c,e.maxLength=f,e.minLength=h,e.mountFormState=P,e.setError=S,e.setMessage=x,e.setValue=O,e.updateFormDataValues=T,e.useFormoose=function(e,o){const[n,a]=t.useState(P(e)),[r,l]=t.useState(),i={cleanError:e=>{C(a,L(e))},convertModelToForm:N,getMaxLength:t=>M(t,e),getModel:e=>k(n,e),getSimpleObject:(e,t)=>A(n,e,t),handleFieldChange:e=>{var t;const o=null===(t=null==e?void 0:e.target)||void 0===t?void 0:t.name;$(e,o,a),l({fieldName:o,fieldValue:e.target.value})},mountFormState:()=>P(e),setError:(e,t)=>S(a,e,t,o),setMessage:(e,t)=>x(a,e,t),setValue:(e,t)=>O(a,e,t),updateFormDataValues:e=>T(n,e),validateAllFieldsSync:()=>j(e,n,a,o),validateOneField:async t=>await I(L(t),e,n,a,o)},s=t.useCallback((e=>({name:e,value:n[e].value,onChange:i.handleFieldChange,onFocus:i.cleanError,onBlur:i.validateOneField})),[i]);return t.useEffect((()=>{clearTimeout(B),(null==r?void 0:r.fieldName)&&(B=setTimeout((()=>{i.validateOneField(r.fieldName)}),500))}),[r]),{formData:n,setFormData:a,setProps:s,...i}},e.validateAllFieldsSync=j,e.validateOneField=I}));
//# sourceMappingURL=index.umd.js.map