Minimal JSON Schema Validator
A dependency free validator for the common JSON Schema subset that reports every violation with its JSON path instead of stopping at the first mismatch.
Code
export interface ValidationIssue {
readonly path: string;
readonly message: string;
}
export type ValidationResult =
| { readonly valid: true }
| { readonly valid: false; readonly issues: ValidationIssue[] };
type Schema = {
readonly type?: "object" | "array" | "string" | "number" | "boolean" | "null";
readonly required?: readonly string[];
readonly properties?: Record<string, Schema>;
readonly items?: Schema;
readonly minLength?: number;
readonly minimum?: number;
readonly enum?: readonly unknown[];
};
function typeOf(value: unknown): string {
if (value === null) return "null";
if (Array.isArray(value)) return "array";
return typeof value;
}
function childPath(path: string, segment: string | number): string {
// 数组下标用方括号,属性用点号——贴近常见 JSON path 书写习惯
if (typeof segment === "number") return path + "[" + segment + "]";
return path === "$" ? "$." + segment : path + "." + segment;
}
export function validate(value: unknown, schema: Schema, path = "$"): ValidationResult {
const issues: ValidationIssue[] = [];
walk(value, schema, path, issues);
return issues.length === 0 ? { valid: true } : { valid: false, issues };
}
function walk(value: unknown, schema: Schema, path: string, issues: ValidationIssue[]): void {
if (schema.type && typeOf(value) !== schema.type) {
issues.push({
path,
message: "expected " + schema.type + " but got " + typeOf(value),
});
return;
}
if (schema.enum && !schema.enum.includes(value)) {
issues.push({ path, message: "value must be one of " + JSON.stringify(schema.enum) });
}
if (schema.type === "string" && typeof value === "string") {
if (schema.minLength !== undefined && value.length < schema.minLength) {
issues.push({ path, message: "string shorter than " + schema.minLength + " characters" });
}
}
if (schema.type === "number" && typeof value === "number") {
if (schema.minimum !== undefined && value < schema.minimum) {
issues.push({ path, message: "number below minimum " + schema.minimum });
}
}
if (schema.type === "object" && value && typeof value === "object" && !Array.isArray(value)) {
const record = value as Record<string, unknown>;
for (const key of schema.required ?? []) {
if (!(key in record)) {
issues.push({ path, message: "missing required property " + key });
}
}
for (const [key, childSchema] of Object.entries(schema.properties ?? {})) {
if (key in record) walk(record[key], childSchema, childPath(path, key), issues);
}
}
if (schema.type === "array" && Array.isArray(value)) {
if (schema.items) {
value.forEach((item, index) => walk(item, schema.items as Schema, childPath(path, index), issues));
}
}
}A hand written if-chain stops at the first bad field, so users fix one error per request instead of seeing everything wrong at once.
Use case: engineers validating API payloads without pulling a validation library
Inputs / outputs
- Input: a JSON Schema subset (type, required, properties, items, minLength, minimum, enum) and a value
- Output: a validation result listing every violation with its JSON path
Error conditions
- type mismatch at any path
- missing required property
- value outside minLength or minimum
- value not in enum
Approach
recursive walk of schema and value; collect violations into an array with a JSON path; only report pass when the list is empty.
Implementation
export interface ValidationIssue {
readonly path: string;
readonly message: string;
}
export type ValidationResult =
| { readonly valid: true }
| { readonly valid: false; readonly issues: ValidationIssue[] };
type Schema = {
readonly type?: "object" | "array" | "string" | "number" | "boolean" | "null";
readonly required?: readonly string[];
readonly properties?: Record<string, Schema>;
readonly items?: Schema;
readonly minLength?: number;
readonly minimum?: number;
readonly enum?: readonly unknown[];
};
function typeOf(value: unknown): string {
if (value === null) return "null";
if (Array.isArray(value)) return "array";
return typeof value;
}
function childPath(path: string, segment: string | number): string {
// 数组下标用方括号,属性用点号——贴近常见 JSON path 书写习惯
if (typeof segment === "number") return path + "[" + segment + "]";
return path === "$" ? "$." + segment : path + "." + segment;
}
export function validate(value: unknown, schema: Schema, path = "$"): ValidationResult {
const issues: ValidationIssue[] = [];
walk(value, schema, path, issues);
return issues.length === 0 ? { valid: true } : { valid: false, issues };
}
function walk(value: unknown, schema: Schema, path: string, issues: ValidationIssue[]): void {
if (schema.type && typeOf(value) !== schema.type) {
issues.push({
path,
message: "expected " + schema.type + " but got " + typeOf(value),
});
return;
}
if (schema.enum && !schema.enum.includes(value)) {
issues.push({ path, message: "value must be one of " + JSON.stringify(schema.enum) });
}
if (schema.type === "string" && typeof value === "string") {
if (schema.minLength !== undefined && value.length < schema.minLength) {
issues.push({ path, message: "string shorter than " + schema.minLength + " characters" });
}
}
if (schema.type === "number" && typeof value === "number") {
if (schema.minimum !== undefined && value < schema.minimum) {
issues.push({ path, message: "number below minimum " + schema.minimum });
}
}
if (schema.type === "object" && value && typeof value === "object" && !Array.isArray(value)) {
const record = value as Record<string, unknown>;
for (const key of schema.required ?? []) {
if (!(key in record)) {
issues.push({ path, message: "missing required property " + key });
}
}
for (const [key, childSchema] of Object.entries(schema.properties ?? {})) {
if (key in record) walk(record[key], childSchema, childPath(path, key), issues);
}
}
if (schema.type === "array" && Array.isArray(value)) {
if (schema.items) {
value.forEach((item, index) => walk(item, schema.items as Schema, childPath(path, index), issues));
}
}
}
Verification tests
import { test } from "node:test";
import assert from "node:assert/strict";
import { validate } from "./example.ts";
const userSchema = {
type: "object" as const,
required: ["id", "email"],
properties: {
id: { type: "number" as const, minimum: 1 },
email: { type: "string" as const, minLength: 5 },
role: { type: "string" as const, enum: ["admin", "member"] },
tags: { type: "array" as const, items: { type: "string" as const, minLength: 1 } },
},
};
test("collects every violation with its JSON path", () => {
const result = validate({ id: 0, email: "ab", role: "owner", tags: ["ok", ""] }, userSchema);
assert.equal(result.valid, false);
if (!result.valid) {
const paths = result.issues.map((i) => i.path).sort();
assert.deepEqual(paths, ["$.email", "$.id", "$.role", "$.tags[1]"]);
}
});
test("passes a conforming document", () => {
const result = validate(
{ id: 7, email: "[email protected]", role: "member", tags: ["a", "b"] },
userSchema,
);
assert.deepEqual(result, { valid: true });
});
test("reports a missing required property", () => {
const result = validate({ id: 3 }, userSchema);
assert.equal(result.valid, false);
if (!result.valid) {
assert.ok(result.issues.some((i) => i.message.includes("missing required property email")));
}
});
test("rejects a type mismatch", () => {
const result = validate("not an object", userSchema);
assert.equal(result.valid, false);
if (!result.valid) {
assert.equal(result.issues[0].message, "expected object but got string");
}
});
Dependencies and running
No external dependencies (standard library only).
Runtime: node >= 18 Entry point: node –experimental-strip-types example.ts
Limitations and error handling
subset only: no allOf, oneOf, pattern, format or refs; no type coercion.
Verification boundary
execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox
Interactive Tools for This Topic
Report a problem with this exampleOpens a pre-filled issue on GitHub.