[英]Joi .custom() validator does not get executed on a not provided field
object 有两个属性:
number
,我们称它为firstField
string
,我们称它为secondField
现在这里是验证要求
firstField
始终是required
的firstField
等于1
时, secondField
是必需的。 当firstField
不为1
时forbidden
这很容易用.when()
解决
但实际上要确定是否需要 secondField,我必须根据 firstField 和验证上下文中的变量进行一些检查。
Joi.object({
firstField: Joi.number().required(),
secondField: Joi.custom((value, helpers) => {
if (firstField === helpers.prefs.context.someValue) {
// test secondField with forbidden and return error when secondField is provided, otherwise return value
}
// test secondField with required and return error when secondField is not provided, otherwise return value
}),
});
现在我的问题是,当我发送时自定义验证器没有被执行:
{
firstField: "test",
}
但我希望它执行
secondField
时,自定义验证器确实得到执行.when()
而不是自定义验证器时,即使未提供secondField
,也会执行 .when .when()
.when("firstField", { is: Joi.any(), then: Joi.any(), otherwise: Joi.any()})
,但还是没有成功我真的试了很多
我看到的最后一个解决方案是将自定义验证器放在字段的父 object 上,并在验证上下文的上下文中测试子字段
解决这个问题的最佳方法是什么? 甚至建议直接在现场测试禁止/要求,还是应该一直在父母身上进行?
根据文档,您可以使用.ref()
访问上下文值:
参考(键,[选项])
如果键以 $ 开头,则表示在上下文选项 object 中查找的上下文引用。
来源: https://joi.dev/api/?v=17.7.0#refkey-options
有了这个,您可以利用when()
来表达您的条件:
Joi.when("firstField", {
is: Joi.ref("$someValue"),
then: Joi.forbidden(),
otherwise: Joi.string(),
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.