Compiling a schema with Ajv
The main Ajv workflow: describe your data with a JSON Schema, compile it into a validation function, and call that function on each value you receive.
How it works
- Describe the data with a schema. The schema requires an integer
foo, allows an optional stringbar, and rejects any other property throughadditionalProperties: false. [1] - Compile once, validate many times.
ajv.compile(schema)returns a function that this example reuses for all six samples. The docs advise compiling each schema once and reusing the function. [1] - Read the errors. The function returns
trueorfalse. When it fails,validate.errorsholds the error objects, andajv.errorsText()turns them into one readable line. [2]
Run and edit it
It runs in your browser, in a sandboxed frame that cannot see this site; the packages load from esm.sh only after you press Run.
import Ajv from "ajv"
const ajv = new Ajv()
const schema = {
type: "object",
properties: {
foo: { type: "integer" },
bar: { type: "string" },
},
required: ["foo"],
additionalProperties: false,
}
// compile once, then reuse the function for every object
const validate = ajv.compile(schema)
const samples = [
{ foo: 1, bar: "abc" },
{ foo: 42 },
{ bar: "abc" },
{ foo: 1.5 },
{ foo: 2, bar: 7 },
{ foo: 3, extra: true },
]
for (const data of samples) {
const valid = validate(data)
console.log(JSON.stringify(data).padEnd(22), valid ? "valid" : "invalid")
if (!valid) console.log(" ", ajv.errorsText(validate.errors))
}
Add a sample such as { foo: "7" } or make bar required and watch which lines turn invalid. Code written by AgentGid [1].
Add a sample such as { foo: "7" } or make bar required and watch which lines turn invalid. Code written by AgentGid [1].Checked Oct 12, 2026: it starts without errors in Chromium with ajv 8.20.0. Needs WebGL.
More Ajv examples
Collecting all errors with Ajv One-call validation with ajv.validate Reusing schemas with addSchema and $ref Custom formats in Ajv
Sources
Explanations written by AgentGid from the official docs; the numbers in brackets point here. The code marked "written by AgentGid" is ours and free to copy.