UNPKG

objectpropvalidator

Version:

Simple, Recursive JavaScript Object Validation with suggestions using console.

2 lines 1.62 kB
// objectPropValidator - A simple, recursive object property validator. This returns true/false and logs specific errors on failure. Copyright (c) 2022 by MAMEDUL ISLAM (https://mamedul.github.io/) Licensed under the MIT license: https://opensource.org/licenses/MIT Project home: https://mamedul.github.io/objectpropvalidator Version: 2.0.1 ;function objectPropValidator(e,r={}){let t=r.logLevel===null?(()=>{}):(console&&console[r.logLevel]||console&&console.error||(()=>{})),o=e=>{if(null===e)return"Null";if(void 0===e)return"Undefined";try{return e.constructor.name}catch(r){return Object.prototype.toString.call(e).slice(8,-1)}};return function r(i){let n=!0;if(null===i||"object"!=typeof i)return t(`[Validation Error] Invalid data provided. Expected 'Object' but received '${o(i)}'.`),!1;for(let a in e){let l=e[a],c=Object.prototype.hasOwnProperty.call(i,a)?i[a]:void 0;if(!l||"object"!=typeof l){t(`[Schema Error] Invalid schema rule for property '${a}'. Expected 'Object'.`),n=!1;continue}if(l.required&&void 0===c){t(`[Validation Error] Missing required property: '${a}'`),n=!1;continue}if(void 0!==c){if(l.type){let d=Array.isArray(l.type)?l.type:[l.type],p=d.map(e=>e.name),u=o(c);if(!p.includes(u)){let f=p.join(" or ");t(`[Validation Error] Invalid type for property '${a}'. Expected '${f}' but received '${u}'.`),n=!1}}if("function"==typeof l.validator)try{l.validator(c)||(n=!1)}catch(y){t(`[Validator Error] An exception occurred while executing custom validator for property '${a}': ${y.message}`),n=!1}}}return n}}"undefined"!=typeof module&&module.exports&&(module.exports=objectPropValidator);