【发布时间】:2019-09-08 11:11:00
【问题描述】:
使用Joi,只有当type 是A 或B 并且subType 是AA 或BB 时,我如何使架构需要rent.max?这是我的尝试。
const Joi = require("joi");
const schema = Joi.object().keys({
type: Joi.string().valid('A', 'B', 'C').required(),
subType: Joi.string().valid('AA', 'BB', 'X'),
rent: Joi.object().keys({
price: Joi.number().required().precision(2),
// max is allowed only when type is A or B
// and subType is AA or BB.
max: Joi.alternatives()
.when('type', {
is: Joi.valid('A', 'B'),
then: Joi.alternatives().when('subType', {
is: Joi.valid('AA', 'BB'),
then: Joi.number(),
otherwise: Joi.forbidden()
}),
otherwise: Joi.forbidden()
})
})
});
const obj = {
type: 'A',
subType: 'AA',
rent: {
price: 3000.25,
max: 300.50,
}
};
const result = Joi.validate(obj, schema);
console.log(result.error);
我预计验证会失败,但事实并非如此。
【问题讨论】:
标签: node.js validation schema joi