JSON Schema Validator — TypeScript source
Validate a JSON document against a draft-07 subset schema: types, required, bounds, patterns, enums, arrays and strict objects, every issue reported at its exact path. Pairs with the schema generator. Runs locally with a shareable link.
This is the TypeScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
// Pure surface of the JSON Schema Validator tool (slug: json-schema-validator).
// Validates a JSON instance against a draft-07 SUBSET schema. The supported
// keywords and the exact error messages below are the contract a Go CLI twin
// must reproduce. Not supported (by design, documented): $ref/$defs, oneOf/
// anyOf/allOf/not, patternProperties, dependencies, format enforcement,
// propertyNames, contains. The companion generator (json-to-schema) never
// emits any of these, so the pair stays coherent.
export interface ValidationIssue {
/** "$"-rooted path of the offending value. */
path: string;
message: string;
}
export type JsonSchemaValidateResult =
| { valid: true; issues: []; error: null }
| { valid: false; issues: ValidationIssue[]; error: null }
| { valid: false; issues: []; error: string };
type Json = null | boolean | number | string | Json[] | { [k: string]: Json };
const KINDS = ['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] as const;
function kindOf(v: Json): (typeof KINDS)[number] {
if (Array.isArray(v)) return 'array';
if (v === null) return 'null';
if (typeof v === 'boolean') return 'boolean';
if (typeof v === 'number') return Number.isInteger(v) ? 'integer' : 'number';
if (typeof v === 'object') return 'object';
return 'string';
}
function deepEqual(a: Json, b: Json): boolean {
if (a === b) return true;
if (kindOf(a) !== kindOf(b)) return false;
if (Array.isArray(a) && Array.isArray(b)) {
return a.length === b.length && a.every((x, i) => deepEqual(x, b[i]));
}
if (a !== null && b !== null && typeof a === 'object' && typeof b === 'object') {
const ao = a as Record<string, Json>;
const bo = b as Record<string, Json>;
const ka = Object.keys(ao);
return ka.length === Object.keys(bo).length && ka.every((k) => k in bo && deepEqual(ao[k], bo[k]));
}
return false;
}
/** Validate one value against one schema node, appending issues with paths. */
function validate(v: Json, schema: unknown, path: string, out: ValidationIssue[]): void {
if (schema === true) return;
if (schema === false) {
out.push({ path, message: 'no value is allowed here (schema is false)' });
return;
}
if (schema === null || typeof schema !== 'object' || Array.isArray(schema)) {
out.push({ path, message: 'invalid schema node: expected an object or boolean' });
return;
}
const s = schema as Record<string, unknown>;
const type = s.type;
if (type !== undefined) {
const allowed = Array.isArray(type) ? type.map(String) : [String(type)];
const actual = kindOf(v);
const ok = allowed.some((t) => t === actual || (t === 'number' && actual === 'integer'));
if (!ok) out.push({ path, message: `expected type ${allowed.join('|')}, got ${actual}` });
}
if (s.enum !== undefined) {
const list = Array.isArray(s.enum) ? (s.enum as Json[]) : [];
if (!list.some((e) => deepEqual(v, e))) {
out.push({ path, message: `value not in enum (${list.length} allowed)` });
}
}
if (s.const !== undefined && !deepEqual(v, s.const as Json)) {
out.push({ path, message: 'value does not match const' });
}
if (typeof v === 'number') {
if (typeof s.minimum === 'number' && v < s.minimum) out.push({ path, message: `${v} is less than minimum ${s.minimum}` });
if (typeof s.maximum === 'number' && v > s.maximum) out.push({ path, message: `${v} is greater than maximum ${s.maximum}` });
if (typeof s.exclusiveMinimum === 'number' && v <= s.exclusiveMinimum) {
out.push({ path, message: `${v} is not greater than exclusiveMinimum ${s.exclusiveMinimum}` });
}
if (typeof s.exclusiveMaximum === 'number' && v >= s.exclusiveMaximum) {
out.push({ path, message: `${v} is not less than exclusiveMaximum ${s.exclusiveMaximum}` });
}
}
if (typeof v === 'string') {
if (typeof s.minLength === 'number' && v.length < s.minLength) {
out.push({ path, message: `string length ${v.length} is less than minLength ${s.minLength}` });
}
if (typeof s.maxLength === 'number' && v.length > s.maxLength) {
out.push({ path, message: `string length ${v.length} is greater than maxLength ${s.maxLength}` });
}
if (typeof s.pattern === 'string') {
try {
if (!new RegExp(s.pattern).test(v)) out.push({ path, message: `string does not match pattern ${s.pattern}` });
} catch {
out.push({ path, message: `invalid pattern in schema: ${s.pattern}` });
}
}
}
if (Array.isArray(v)) {
if (typeof s.minItems === 'number' && v.length < s.minItems) {
out.push({ path, message: `array length ${v.length} is less than minItems ${s.minItems}` });
}
if (typeof s.maxItems === 'number' && v.length > s.maxItems) {
out.push({ path, message: `array length ${v.length} is greater than maxItems ${s.maxItems}` });
}
if (s.uniqueItems === true) {
for (let i = 0; i < v.length; i++) {
for (let j = i + 1; j < v.length; j++) {
if (deepEqual(v[i], v[j])) {
out.push({ path: `${path}[${j}]`, message: `duplicate item (same as index ${i})` });
}
}
}
}
if (s.items !== undefined) {
v.forEach((item, i) => validate(item, s.items, `${path}[${i}]`, out));
}
}
if (v !== null && typeof v === 'object' && !Array.isArray(v)) {
if (Array.isArray(s.required)) {
for (const key of s.required.map(String)) {
if (!(key in v)) out.push({ path, message: `missing required property "${key}"` });
}
}
const props = (s.properties ?? {}) as Record<string, unknown>;
for (const key of Object.keys(props)) {
if (key in v) validate(v[key], props[key], `${path}.${key}`, out);
}
if (s.additionalProperties === false) {
const known = new Set(Object.keys(props));
for (const key of Object.keys(v)) {
if (!known.has(key)) out.push({ path: `${path}.${key}`, message: 'additional property not allowed' });
}
}
}
}
/** Validate a JSON document (instanceRaw) against a schema (schemaRaw). */
export function validateJsonSchema(schemaRaw: string, instanceRaw: string): JsonSchemaValidateResult {
if (!schemaRaw.trim() || !instanceRaw.trim()) {
return { valid: false, issues: [], error: 'Both a schema and an instance are required' };
}
let schema: Json;
let instance: Json;
try {
schema = JSON.parse(schemaRaw) as Json;
} catch (e) {
const msg = e instanceof Error ? e.message : 'Invalid JSON';
return { valid: false, issues: [], error: `Schema: ${msg}` };
}
try {
instance = JSON.parse(instanceRaw) as Json;
} catch (e) {
const msg = e instanceof Error ? e.message : 'Invalid JSON';
return { valid: false, issues: [], error: `Instance: ${msg}` };
}
const issues: ValidationIssue[] = [];
validate(instance, schema, '$', issues);
return issues.length === 0
? { valid: true, issues: [], error: null }
: { valid: false, issues, error: null };
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →