Recently, I delved into using Ajv with ajv-errors to validate JSON schema and generate personalized error messages. While everything is functioning correctly so far, I encountered a challenge in setting custom error messages for individual values based on type.
const emailSchema = {
type: 'object',
required: ['foo', 'bar', 'car'],
properties: {
foo: { type: 'integer' },
bar: { type: 'string' },
car: { type: 'string' }
},
errorMessage: {
type: 'should be an object',
required: {
foo: 'foo field is missing',
bar: 'bar field is missing',
car: 'car field is missing'
}
}
};
The current output displays the following errors:
[
{
"keyword": "type",
"dataPath": "/foo",
"schemaPath": "#/properties/foo/type",
"params": {
"type": "integer"
},
"message": "should be integer"
},
{
"keyword": "errorMessage",
"dataPath": "",
"schemaPath": "#/errorMessage",
"params": {
"errors": [
{
"keyword": "required",
"dataPath": "",
"schemaPath": "#/required",
"params": {
"missingProperty": "bar"
},
"message": "should have required property 'bar'"
}
]
},
"message": "bar field is missing"
},
{
"keyword": "errorMessage",
"dataPath": "",
"schemaPath": "#/errorMessage",
"params": {
"errors": [
{
"keyword": "required",
"dataPath": "",
"schemaPath": "#/required",
"params": {
"missingProperty": "car"
},
"message": "should have required property 'car'"
}
]
},
"message": "car field is missing"
}
]
In particular, the first error message stating "should be integer" is not specific enough. Is there a way to customize it to something like "foo must be an Integer"? Unfortunately, my attempt was unsuccessful as it resulted in a schema error.
type : {
foo : "foo must be an Integer"
}
Any insights or solutions would be greatly appreciated!