繁体   English   中英

Joi.custom() 验证器不会在未提供的字段上执行

[英]Joi .custom() validator does not get executed on a not provided field

要求

object 有两个属性:

  • 一个number ,我们称它为firstField
  • 一个string ,我们称它为secondField

现在这里是验证要求

  • firstField始终是required
  • firstField等于1时, secondField是必需的。 firstField不为1forbidden

这很容易用.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM