ajv-errors
Custom error messages in JSON-Schema for Ajv validator
Install
npm install ajv-errors
Usage
Add the keyword errorMessages
to Ajv instance:
var Ajv = require('ajv');
var ajv = new Ajv({allErrors: true});
require('ajv-errors')(ajv);
Replace all errors in the current schema and subschemas with a single message:
var schema = {
type: 'object',
required: ['foo'],
properties: {
foo: { type: 'integer' }
},
additionalProperties: false,
errorMessage: 'should be an object with an integer property foo only'
};
var validate = ajv.compile(schema);
console.log(validate({foo: 'a', bar: 2}));
console.log(validate.errors);
Processed errors:
[
{
keyword: 'errorMessage',
message: 'should be an object with an integer property foo only',
params: {
errors: [
{ keyword: 'additionalProperties', dataPath: '' },
{ keyword: 'type', dataPath: '.foo' }
]
}
}
]
Replace errors for certain keywords in the current schema only:
var schema = {
type: 'object',
required: ['foo'],
properties: {
foo: { type: 'integer' }
},
additionalProperties: false,
errorMessage: {
type: 'should be an object',
required: 'should have property foo',
additionalProperties: 'should not have properties other than foo'
}
};
var validate = ajv.compile(schema);
console.log(validate({foo: 'a', bar: 2}));
console.log(validate.errors);
Processed errors:
[
{
keyword: type,
dataPath: '.foo',
message: 'should be integer'
},
{
keyword: 'errorMessage',
message: 'should not have properties other than foo',
params: {
errors: [
{ keyword: 'additionalProperties' }
]
},
}
]
License
MIT