Skip to content
Agents tracked: 440 Downloads (7d): 202M down 19.5% GitHub stars: 10.4M Releases (7d): 607 Agent status: 3 with issuesSince last limit reset: Claude 28d · Codex 0d Updated Oct 21, 2026

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.

All Ajv examples Ajv: usage and stats

Compiling a schema with Ajv: screenshot of the example below running
The code below, running in Chromium on our server (Oct 12, 2026). Press Run to see it live and change it.

How it works

  1. Describe the data with a schema. The schema requires an integer foo, allows an optional string bar, and rejects any other property through additionalProperties: false. [1]
  2. 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]
  3. Read the errors. The function returns true or false. When it fails, validate.errors holds the error objects, and ajv.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))
}
Ctrl/⌘ + Enter runs

Free for signed-in members, with a daily limit. Describe the change in plain words; the new code runs only in your browser.

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

  1. Docs: guide › getting-started.html
  2. Docs: api.html

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.

Building something with Ajv? Ask AgentGid →