Collecting all errors with Ajv
Options are passed to the Ajv constructor. The allErrors option makes the validation function collect every problem in the data, which is what you usually want for form feedback.
How it works
- Create two instances. Options go into the constructor. This example builds one instance with no options and one with
{ allErrors: true }, then compiles the same schema with both. [1] - Compare the error lists. The same invalid object is validated twice. In the output, the default instance reports a single error while the
allErrorsinstance lists the empty name, the negative age, the wrong email type and the missing role. [2] - Print each error. Each error object carries the reason it failed. The loop passes errors one at a time to
ajv.errorsText()to print one line per problem. [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 schema = {
type: "object",
properties: {
name: { type: "string", minLength: 1 },
age: { type: "integer", minimum: 0 },
email: { type: "string" },
},
required: ["name", "age", "email", "role"],
}
const data = { name: "", age: -3, email: 42 }
console.log("data:", JSON.stringify(data))
const instances = [
["default", new Ajv()],
["allErrors", new Ajv({ allErrors: true })],
]
for (const [label, ajv] of instances) {
const validate = ajv.compile(schema)
validate(data)
console.log("")
console.log(`${label}: ${validate.errors.length} error(s)`)
for (const err of validate.errors) {
console.log(" -", ajv.errorsText([err]))
}
}
Fix one field in data at a time and watch the allErrors list shrink while the default count stays at one until everything passes. Code written by AgentGid [1].
Fix one field in data at a time and watch the allErrors list shrink while the default count stays at one until everything passes. 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 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.