【问题标题】:Joi - Required based on value on other keyJoi - 根据其他键上的值需要
【发布时间】:2020-03-25 15:29:03
【问题描述】:

我想验证一个只有两个字段(即文本和图像)的输入。 textimage 都是字符串,其中一个必须始终存在。当其中一个字段不存在时,另一个字段不能是空字符串。 这是我定义的验证。

text: Joi.string()
    .when('image',
        {
            is: Joi.string(),
            then: Joi.string().allow(''),
            otherwise: Joi.string().required(),
        }
    ),
image: Joi.string().allow(null),

当我使用以下输入时,验证允许数据通过。我不知道如何更改验证以禁止以下输入。

post: {
    text: ''
}

【问题讨论】:

  • @James 我使用了 'exist()' 并且它有效。请发表您的评论作为答案,以便我标记您的答案。

标签: node.js joi


【解决方案1】:

验证时使用exist() 而不是string()

when('image', {
  is: Joi.exist(),
  then: Joi.string().allow(''),
  otherwise: Joi.string().required(),
})

【讨论】:

    猜你喜欢
    • 2020-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    相关资源
    最近更新 更多