Explorer
Node.js

Write a basic `validate(schema, data)` that checks if data matches the schema. Support types: "string", "number", "boolean", "object" (with properties), "array".

Problem Statement

Write a basic `validate(schema, data)` that checks if data matches the schema. Support types: "string", "number", "boolean", "object" (with properties), "array".

Complexity

Time Complexity: -

Space Complexity: -

Hints

šŸ’” Hint 1: Check the schema type against typeof data. šŸ’” Hint 2: For "object" type, recursively validate each property in schema.properties. šŸ’” Hint 3: Handle nested objects by recursing. Handle required fields. āœ… Solution: ```javascript function validate(schema, data) { const errors = []; function check(s, d, path) { if (s.type === "object") { if (typeof d !== "object" || d === null) { errors.push(`${path}: expected object`); return; } if (s.properties) { for (const key in s.properties) { check(s.properties[key], d[key], `${path}.${key}`); } } } else if (s.type === "array") { if (!Array.isArray(d)) errors.push(`${path}: expected array`); } else if (typeof d !== s.type) { errors.push(`${path}: expected ${s.type}, got ${typeof d}`); } } check(schema, data, "root"); return { valid: errors.length === 0, errors }; } ```

JSON Schema Validator

Hard
Write a basic `validate(schema, data)` that checks if data matches the schema. Support types: "string", "number", "boolean", "object" (with properties), "array".
Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
[true,false,1]