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