UNPKG

json-deep-compare

Version:

A powerful library for comparing JSON objects with support for deep comparison, regex validation, and customizable options

1 lines 1.29 kB
const PathUtils=require("./PathUtils");class RegexValidator{constructor(e,t){this.options=e,this.result=t}validateValue(e,t){if("string"==typeof e)for(const[s,a]of Object.entries(this.options.regexChecks)){let h=!1;if(s===t)h=!0;else if(this.options.matchKeysByName){PathUtils.getKeyNameFromPath(t)===s&&(h=!0)}h&&this._checkRegex(e,t,a)}}_checkRegex(e,t,s){s.test(e)?this.result.addPassedRegexCheck({path:t,value:e,pattern:s.toString()}):this.result.addFailedRegexCheck({path:t,value:e,pattern:s.toString(),message:"Value does not match regex pattern"})}validateAllMatchingKeys(e){if(!this.options.matchKeysByName)return;const t=PathUtils.getAllPaths(e);for(const[s,a]of Object.entries(this.options.regexChecks)){const h=t.filter((e=>PathUtils.getKeyNameFromPath(e)===s));for(const t of h){const s=PathUtils.getValueAtPath(e,t);if("string"==typeof s){this._isPathChecked(t)||(a.test(s)?this.result.addPassedRegexCheck({path:t,value:s,pattern:a.toString(),matchedByName:!0}):this.result.addFailedRegexCheck({path:t,value:s,pattern:a.toString(),message:"Value does not match regex pattern",matchedByName:!0}))}}}}_isPathChecked(e){const t=this.result.getResult();return t.regexChecks.passed.some((t=>t.path===e))||t.regexChecks.failed.some((t=>t.path===e))}}module.exports=RegexValidator;