Joi的ref文档建议使用
Joi.ref
创建的Reference可以引用上下文对象中的值。Joi的any.when文档建议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')
。文件中的详细信息
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);