Reusing schemas with addSchema and $ref
Schemas added to an Ajv instance under a key can be referenced from other schemas with $ref and fetched later as ready validation functions.
How it works
- Register schemas under keys.
ajv.addSchema(schema, "address")stores the address schema under the keyaddress; the user schema is stored asuser. [1] - Point to it with $ref. The user schema uses
{ $ref: "address" }for bothhomeandwork, so the zip pattern and the required city are written only once. [1] - Get a validation function by key.
ajv.getSchema("user")returns a function that works like one fromcompile. The last line asks for a key that was never added and printsundefined. [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()
// register reusable schemas under string keys
ajv.addSchema({
type: "object",
properties: {
city: { type: "string" },
zip: { type: "string", pattern: "^[0-9]{5}$" },
},
required: ["city", "zip"],
}, "address")
ajv.addSchema({
type: "object",
properties: {
name: { type: "string" },
home: { $ref: "address" }, // points at the schema added above
work: { $ref: "address" },
},
required: ["name", "home"],
}, "user")
const validateUser = ajv.getSchema("user")
const validateAddress = ajv.getSchema("address")
const users = [
{ name: "Ana", home: { city: "Lisbon", zip: "10001" } },
{ name: "Ben", home: { city: "Oslo", zip: "0150" } },
{ name: "Cy", home: { city: "Rome", zip: "00118" }, work: { zip: "20121" } },
{ name: "Dee" },
]
for (const u of users) {
const ok = validateUser(u)
console.log(`${u.name}: ${ok ? "valid" : ajv.errorsText(validateUser.errors)}`)
}
console.log("address only:", validateAddress({ city: "Paris", zip: "75001" }))
console.log("unknown key:", ajv.getSchema("order"))
Change the zip pattern in the address schema once and both home and work addresses follow it. Code written by AgentGid [1].
Change the zip pattern in the address schema once and both home and work addresses follow it. 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 One-call validation with ajv.validate 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.