首页 > 解决方案 > 条件未按预期工作时的 JOI 验证

问题描述

我定义了以下 JOI 模式;

schema = Joi.object({
  flag: Joi.boolean()
    .required(),
  toolDetail: Joi.array().items(
    Joi.object({
      amount: Joi.number()
        .min(0)
        .max(499.99)
        .precision(2)
        .options({ convert: false })
        .when('flag', {
          is: true,
          then: Joi.number().required(),
          otherwise: Joi.number()
            .strip()
            .optional()
            .allow(''),
        }),
      tool: Joi.string()
        .min(0)
        .max(500)
        .when('flag', {
          is: true,
          then: Joi.string().required(),
          otherwise: Joi.string()
            .strip()
            .optional()
            .allow(''),
        }),
    }),
  ),
});

我已经确认标志设置正确,但无论“标志”中设置的值如何,“数量”和“工具”似乎总是达到其他条件。

我的定义有什么不正确的吗?

标签: joi

解决方案


一旦我在标志上添加了 4 个点前缀,就可以按预期工作

.when('....flag', { 

https://joi.dev/api/?v=17.2.1#relative-references


推荐阅读