custom-joi-error
v1.0.0
Published
Customize Joi errors, by stripping quotes and setting key specific error language.
Downloads
2
Readme
custom-joi-error
Customize Joi errors, by stripping quotes and setting key specific error language.
Installation
npm install custom-joi-error
Usage
Call customJoiError
function with Joi's validation result as first arguments.
You can pass options as second argument.
const customJoiError = require('custom-joi-error');
/** Or with ES6+ */
import customJoiError from 'custom-joi-error';
const result = Joi.validate(
{ firstName: '', lastName: 10 },
{
firstName: Joi.string()
.not()
.empty()
.label('Fist name'),
lastName: Joi.string()
.not()
.empty()
.label('Last name')
}
);
if (result.error) {
throw customJoiError(result, {
language: {
firstName: {
'any.empty': 'Please enter a first name'
}
}
});
}
It will return:
Error (CustomValidationError) {
message: 'Please enter a first name, Last name must be a string',
details: [
{
message: 'Please enter a first name',
path: [ 'firstName' ],
type: 'any.empty',
context: {
value: '',
invalids: [ '' ],
key: 'firstName',
label: 'First name'
},
},
{
message: 'Last name must be a string',
path: [ 'lastName' ],
type: 'any.empty',
context: {
value: 10,
key: 'lastName',
label: 'Last name'
},
},
],
}
Options
stripQuotes
(default:true
) Remove quote from key label in error message.language
(default:{}
) Set key specific error message, example :
{
language: {
name: {
string: {
email: 'Please enter a valid email'
}
}
}
}
See Joi language file for full messages list.
Build
npm run build
Testing
npm test
Related
- joi - Object schema validation
License
This project is licensed under the MIT license.