【问题标题】:hapijs Joi when one field is non empty other fields must be requiredhapijs Joi 当一个字段不为空时,其他字段必须是必需的
【发布时间】:2018-04-30 23:34:42
【问题描述】:

当密码不为空时,意味着需要其他两个字段。在某些情况下,密码将存在但将为空,在这种情况下,不需要其他两个字段。我尝试了存在()和!empty(),但它不起作用。

password : joi.string().trim().optional().description('Password'), device_type : joi.when('password', {is: (joi.exist() && !joi.empty()), then: joi.number().required().valid(validation.user.device_type.allowOnly).description('Device type')}), device_token : joi.when('password', {is: joi.exist(), then: joi.string().trim().required().description('Device token')})

但这行不通

【问题讨论】:

    标签: hapijs joi


    【解决方案1】:

    您的问题分为两部分:

    1. 将密码的空字符串视为根本没有提交密码。见any.empty(...)
    2. 只要存在另一个密码,就需要密钥。见object.with(...)

    为了清楚起见,将它们放在一起并简化您的架构(注意所有键默认情况下都是可选的):

    const schema = joi.object({
        password      : joi.string().trim().empty(''),
        device_type   : joi.number(),
        device_token  : joi.string().trim()
    }).with('password', ['device_type', 'device_token']);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-23
      • 2018-07-03
      • 1970-01-01
      • 2018-01-18
      • 1970-01-01
      • 1970-01-01
      • 2015-08-07
      • 1970-01-01
      相关资源
      最近更新 更多