Skip to main content
Version: 1.3.0

JSON Schema Validation

Schemas use a subset of JSON Schema for validation. This keeps the validator small and fully serializable (no $ref resolution, no remote fetching).

Supported keywords

KeywordApplies toDescription
typeanyExpected type(s). Array form for nullable: ["string", "null"]
enumanyValue must be deeply equal to one entry
constanyValue must be deeply equal to this exact value
minimumnumber / integerInclusive lower bound
maximumnumber / integerInclusive upper bound
exclusiveMinimumnumber / integerExclusive lower bound
exclusiveMaximumnumber / integerExclusive upper bound
minLengthstringMinimum string length (inclusive)
maxLengthstringMaximum string length (inclusive)
propertiesobjectProperty-name → sub-schema mapping
requiredobjectProperties that must be present
additionalPropertiesobjectfalse to disallow extras, or a sub-schema
itemsarraySchema applied to every element
minItemsarrayMinimum array length (inclusive)
maxItemsarrayMaximum array length (inclusive)

Defining a schema

Schemas are plain JSON objects — fully serializable, no functions.

import type { KeySchema } from "react-mnemonic/schema";

const profileSchema: KeySchema = {
key: "profile",
version: 1,
schema: {
type: "object",
properties: {
name: { type: "string", minLength: 1 },
email: { type: "string" },
age: { type: "number", minimum: 0 },
},
required: ["name", "email"],
},
};

Standalone validation

Use validateJsonSchema to validate any value against a schema outside of the hook:

import { validateJsonSchema } from "react-mnemonic/schema";

const errors = validateJsonSchema(
{ name: 42 },
{ type: "object", properties: { name: { type: "string" } }, required: ["name"] },
);
// [{ path: "/name", message: 'Expected type "string", got "number"' }]

Compiled validators

For performance-sensitive code paths, pre-compile a schema into a reusable validator function with compileSchema. The compiled validator is cached by schema reference (WeakMap), so repeated calls with the same object return the identical function.

import { compileSchema } from "react-mnemonic/schema";
import type { CompiledValidator } from "react-mnemonic/schema";

const validate: CompiledValidator = compileSchema({
type: "object",
properties: {
name: { type: "string", minLength: 1 },
age: { type: "number", minimum: 0 },
},
required: ["name"],
});

validate({ name: "Alice", age: 30 }); // []
validate({ age: -1 }); // [{ path: "", … }, { path: "/age", … }]

This is useful when you validate the same schema frequently outside of the hook (e.g. in form validation or server responses). Internally, the hook already uses compiled validators for all schema checks.