[英]Joi Validations: Capture the value passed in Custom Error Message
I am using Joi Library with NodeJs/Typescript for validations. 我正在使用带有NodeJs / Typescript的Joi库进行验证。 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 如何捕获在自定义错误消息中作为requestBody传递的错误字段值
For eg if I pass request body for the POST endpoint 例如,如果我传递POST端点的请求正文
{
"field1": "wrongvalue",
}
Expected custom message Invalid value 'wrongvalue' for parameter \\'field1\\'. 预期的自定义消息参数\\'field1 \\'的无效值'wrongvalue'。 It must be \\'Dummy\\''
它必须是\\'Dummy \\'
I have gone through JOI API but could not find any reference to doing this. 我已经通过JOI API,但是找不到任何参考。 While regex option has the facility to capture the value passed.
正则表达式选项具有捕获传递的值的功能。 {{value}} works in regex but not in other options.
{{value}}适用于正则表达式,但不适用于其他选项。
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;
}),
}) })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.