One-call validation with ajv.validate
ajv.validate checks data against a schema in one call, without a separate compile step, and leaves the errors on the Ajv instance.
How it works
- Validate in one call.
ajv.validate(productSchema, p)takes the schema and the data together and returns a boolean. The schema is compiled and cached on the first call. [1] - Read errors from the instance. With this method the errors live on
ajv.errorsrather than on a function. For the valid product the example printsnull. [1] - Copy errors you need later. Every call replaces
ajv.errors, so the loop pushes each error array intosavedand prints them all at the end. [1]
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 productSchema = {
type: "object",
properties: {
sku: { type: "string", pattern: "^[A-Z]{3}-[0-9]{3}$" },
price: { type: "number", exclusiveMinimum: 0 },
tags: { type: "array", items: { type: "string" }, maxItems: 3 },
},
required: ["sku", "price"],
}
const products = [
{ sku: "ABC-123", price: 9.5, tags: ["new"] },
{ sku: "abc-1", price: 4 },
{ sku: "XYZ-999", price: 0 },
{ sku: "XYZ-999", price: 5, tags: ["a", "b", "c", "d"] },
{ price: 12 },
]
const saved = []
products.forEach((p, i) => {
// no compile step: the schema is passed with the data
const ok = ajv.validate(productSchema, p)
console.log(`product ${i + 1}: ${ok ? "valid" : "invalid"}`)
if (ok) console.log(" ajv.errors =", ajv.errors)
else saved.push([i + 1, ajv.errors]) // keep a reference before the next call
})
console.log("--- saved errors ---")
for (const [n, errs] of saved) {
console.log(`product ${n}:`, ajv.errorsText(errs))
}
Remove the saved.push line and print ajv.errors after the loop to see that only the last result is left. Code written by AgentGid [1].
Remove the saved.push line and print ajv.errors after the loop to see that only the last result is left. 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
Compiling a schema with Ajv Collecting all errors with Ajv 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.