JSFiddle - React, Tailwind, and code Playground
by DeadByElpy
JavaScript
'use strict';
let errors, dataSchema;
const validateSchema = ( data, nestedPath = [] ) => {
const originalData = data;
let schema = dataSchema;
console.log({originalData});
console.log({nestedPath});
if ( nestedPath.length ) {
nestedPath.forEach(nestedProperty => {
data = data[nestedProperty];
schema = schema[nestedProperty];
});
}
console.log({data});
console.log({schema});
if ( Array.isArray(schema) && !Array.isArray(data) ) {
errors.push(`field '${nestedPath.join('.')}.${data} should be an array'`);
return;
}
if ( typeof schema === 'number' && typeof data !== 'number' ) {
errors.push(`field '${nestedPath.join('.')}.${data} should be an number'`);
return;
}
if ( typeof schema === 'string' && typeof data !== 'string' ) {
errors.push(`field '${nestedPath.join('.')}.${data} should be an string'`);
return;
}
Object.keys(schema).forEach(property => {
if ( property in data ) {
console.log(`check ${property} in data`);
const type = schema[property].constructor.name;
if ( type !== data[property].constructor.name ) {
errors.push(`field '${nestedPath.join('.')}.${property} should be a type ${type}'`);
return;
}
if ( type === 'Object' ) {
console.log(`${property} is object`);
// avoid modification in recursive calls
validateSchema(originalData, [...nestedPath, property]);
} else if ( type === 'Array') {
console.log(`${property} is array`);
console.log(`${schema[property].length}`);
if ( schema[property].length === 0 ) {
// optional array
return;
}
if ( schema[property].length > 0 && data[property].length === 0 ) {
...