hapijs Joi 当一个字段非空时其他字段必须是必需的

hapijs Joi when one field is non empty other fields must be required

当密码为非空时表示需要另外两个字段。在某些情况下,密码将存在但将为空,在这种情况下,不需要其他两个字段。我尝试使用 exist() 和 !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')})

但这行不通

您的问题分为两部分:

  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']);