I am using Joi Library with NodeJs/Typescript for validations. Validating a request body for a Post Operation.
I am using the language option to provide custom messages for respective field validations.
Below is the code
const bodySchema = Joi.object().keys({
// had to change from string to any so as to avoid multiple messages when empty
field1: Joi.any().required().valid('Dummy').options({
language: {
any: {
// wrt empty: specific error message not displaying with any but empty error is handled by allowOnly custom message. Anways there is no custom message for empty in requirements
// empty: '!!The parameter \'field1\' cannot be empty. It must be \'Dummy\'',
required: '!!The parameter \'field1\' is mandatory and must be the value \'Dummy\'',
allowOnly: '!!Invalid value for parameter \'field1\'. It must be \'Dummy\''
// how to capture value passed for field1 in the message?
}
}
}),
How to Capture the wrong field value passed as requestBody in the custom error message
For eg if I pass request body for the POST endpoint
{
"field1": "wrongvalue",
}
Expected custom message Invalid value 'wrongvalue' for parameter \\'field1\\'. It must be \\'Dummy\\''
I have gone through JOI API but could not find any reference to doing this. While regex option has the facility to capture the value passed. {{value}} works in regex but not in other options.
Please let me know if there is a way to capture the value.
try this ......
const typeSchema = Joi.object({field1: Joi
any()
.required()
.valid('Dummy')
.error(errors => {
errors.forEach(err => {
switch (err.type) {
case "string.base":
case "required":
err.message = "field 1 is mandatory and must be the value";
break;
case "any.allowOnly":
err.message = "field1 must be Dummy";
break;
default:
console.log('validate error type missing', err.type);
break;
}
});
return errors;
}),
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.