Ajv is a JavaScript library that turns JSON Schema definitions into validation functions. It helps boundary data fail clearly instead of leaking malformed requests into the system. section 7.6
When a search request goes wrong
A request uses myTitle instead of title. After validation, ajv.errors contains structured details such as the missing property. Call ajv.errorsText(ajv.errors) to produce a readable message. By default, Ajv reports the first failure; construct it with {allErrors: true} to collect several failures, including invalid array items. section 7.5
Listing 7.23 Catching multiple validation failures
var searchBooksRequestSchema = {
"type": "object",
"properties": {
"title": {"type": "string"},
"fields": {
"type": "array",
"items": {"type": "string"}
}
},
"required": ["title", "fields"]
};
var invalidSearchBooksRequest = { #1
"myTitle": "habit",
"fields": [1, 2]
};
var ajv = new Ajv({allErrors: true}); #2
ajv.validate(searchBooksRequestSchema,
invalidSearchBooksRequest);
ajv.errorsText(ajv.errors); #3
// → "data must have required property 'title',
// → data/fields/0 must be string,
// → data/fields/1 must be string"
A compact listing shows how allErrors changes validation from one reported problem to a readable set of failures. section 7.5
