【问题标题】:Joi how to validate a field should be emptyJoi如何验证一个字段应该是空的
【发布时间】:2019-06-10 21:58:24
【问题描述】:

当角色是“学生”时,parentemail 是必需的。否则它应该是空的。

当我提供parentemail 时,以下内容不起作用。

如何验证字段是否为空,如果不为空,则会发生错误。

parentemail: Joi.string().email().when("role", {
      is: "student",
      then: Joi.required(),
      otherwise: Joi.empty(undefined)
    }),

【问题讨论】:

    标签: joi


    【解决方案1】:

    我不确定您对Joi.empty() 的使用是否正确。文档说:

    any.empty(schema)

    将与架构匹配的任何内容视为空(未定义)。

    这表明它应该被用来扩展 Joi 对“空”定义的看法。

    尝试类似的方法:

    Joi.object().keys({
        role: Joi.string(),
        parentemail: Joi.when('role', {
            is: 'student',
            then: Joi.string().email().required(),
            otherwise: Joi.string().valid([ null, '' ])
        })
    })
    

    role'student' 时,这将只允许parentemailundefinednull''(类似“空”的值)。

    或者,当role'student' 时,您可以通过将otherwise 更改为

    来完全禁止parentemail
    otherwise: Joi.forbidden()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-22
      • 2020-09-06
      • 2019-01-22
      • 1970-01-01
      • 2019-05-01
      • 2016-05-31
      • 2019-04-28
      • 2020-10-23
      相关资源
      最近更新 更多