如何根据上下文中的值创建 Joi `when` 条件?

How can you base a Joi `when` condition on a value from the context?

Joi 的 ref documentation suggests that a Reference created using Joi.ref can refer to a value from the context object. Joi's any.when documentation 建议 condition 参数接受引用。但是,我无法使用以下简单用法:

import Joi from "joi";

const schema = Joi.object({
  year: Joi.number().when(Joi.ref(`$flag`), {
    is: Joi.boolean().truthy,
    then: Joi.number().min(2000),
  }),
});

const value = {
  year: 1999,
};

const context = {
  flag: true
};

const result = schema.validate(value, { context });

此代码导致通过验证。但是,我希望它会失败。我错过了什么?

您需要使用 boolean().valid(true) 所以只有布尔值 true 通过!

boolean().truthy() 接受 附加值 的列表,这些值被视为有效的布尔值。例如。 boolean().truthy('YES', 'Y')。详情在Documentation

joi版本:17.2.1

const Joi = require('joi');

const schema = Joi.object({
  year: Joi.number().when(
    Joi.ref('$flag'), {
      is: Joi.boolean().valid(true), then: Joi.number().min(2000),
    },
  ),
});

const value = {
  year: 1999,
};

// fails
const context = {
  flag: true
};

// passes
const context = {
  flag: false
};

const result = schema.validate(value, { context });
console.log(result.error);