如何强制一个属性仅在另一个属性为真时出现?

How to force an attribute to be present only if another one is true?

我正在尝试使用 Joi 验证一个简单的对象。我定义的模式如下:

const singleReq = Joi.object({  
    subscribing: Joi.boolean(),  
    duration: Joi.number().integer().positive(),
});

我希望 duration 仅在 subscribing 为真时出现(非空)。我正在尝试用断言来做,但我不知道怎么做。

您可以尝试以下操作:

const singleReq = Joi.object({  
  subscribing: Joi.boolean(),  
  duration: Joi.number()
  .when('subscribing', { is: true, then: Joi.integer().positive().required() })
});

如果你想改变类型,你也可以尝试使用如下示例的替代方法:

const schema = {
  a: Joi.alternatives().when('b', { is: 5, then: Joi.string(), otherwise: Joi.number() }),
  b: Joi.any()
};

references