Better error messages for Hapi.js Joi validation
Joi provides awesome schema validation, but the error messages returned are not user-friendly. This package returns a more user-friendly version of Joi's default response and allows for custom error messages.
Default Joi Response
{
"statusCode": 400,
"error": "Bad Request",
"message": "child \"data\" fails because [child \"name\" fails because [\"name\" is not allowed to be empty], child \"email\" fails because [\"email\" must be a valid email]]",
"validation": {
"source": "payload",
"keys": [
"data.name",
"data.email"
]
}
}
Example Relish Response
{
"statusCode": 400,
"error": "Bad Request",
"message": "\"name\" is not allowed to be empty, \"email\" must be a valid email",
"validation": {
"source": "payload",
"errors": [
{
"key": "name",
"path": "data.name",
"message": "\"name\" is not allowed to be empty",
"type": "any",
"constraint": "required"
},
{
"key": "email",
"path": "data.email",
"message": "\"email\" must be a valid email",
"type": "string",
"constraint": "email"
}
]
}
}
npm install relish --save
First load and initialize the module
// load the package and set custom message options
const Relish = require('relish')({
messages: {
'data.name': 'Please enter your full name'
}
});
Once initialized, this package exposes a custom failAction
handler that can be used in your Hapi.js Route Options.
// call the failAction handler in your route options
server.route({
method: 'POST',
path: '/',
config: {
validate: {
// set a custom failAction handler
failAction: Relish.failAction,
payload: {
data: Joi.object({
name: Joi.string().required(),
email: Joi.string().email()
})
}
}
},
handler: (request, reply) => reply()
});
You can apply this module to all routes by setting the failAction in your server connection options.
server.connection({
// ... other connection options
routes: {
validate: {
failAction: Relish.failAction
}
}
});
See the API Documentation for reference.