我正在使用 Joi 库和 NodeJs/Typescript 进行验证。 验证 Post 操作的请求正文。
我使用语言选项为各个字段验证提供自定义消息。
下面是代码
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?
}
}
}),
如何捕获自定义错误消息中作为 requestBody 传递的错误字段值
例如,如果我传递 POST 端点的请求正文
{
"field1": "wrongvalue",
}
预期的自定义消息 参数“field1”的值“wrongvalue”无效。它必须是“虚拟”
我已经浏览了 JOI API,但找不到任何执行此操作的引用。 而正则表达式选项可以捕获传递的值。 {{value}} 在正则表达式中有效,但在其他选项中无效。
请告诉我是否有办法捕获该值。
最佳答案
试试这个......
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;
}),
})
关于javascript - Joi 验证 : Capture the value passed in Custom Error Message,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49914806/