TIL: Validating JSON Schemas With Ajv in Node.js
API requests arrive as JSON. Before you trust that data, validate its shape. Ajv does that against a JSON Schema definition.
const Ajv = require('ajv')
const ajv = new Ajv()
const schema = {
type: 'object',
properties: {
to: { type: 'string' },
text: { type: 'string', maxLength: 160 },
type: { enum: ['sms', 'voice'] }
},
required: ['to', 'text']
}
const validate = ajv.compile(schema)
const input = { to: '+44123456789', text: 'Hello' }
if (validate(input)) {
console.log('Valid payload')
} else {
console.log('Validation failed:', validate.errors)
}
Ajv compiles schemas into validation functions. Calling them is fast because the compilation happens once. The error output tells you exactly which field failed and why.
Does Ajv support draft 7?
Yes. As of 2019 Ajv supported JSON Schema draft 7 with all the keyword features.
Can I validate async?
Ajv supports async validation with the format keyword for custom validators that return Promises.