【发布时间】:2017-05-31 01:43:06
【问题描述】:
有没有办法使用 Joi 来表达数据中的关系?
例如
const schema = ({
min: number(),
max: number(),
});
我可以添加一条验证规则,上面写着data.min < data.max吗?
编辑:添加示例
Ankh 的示例对我很有帮助,因为文档有点精简。 Joi tests for ref 帮助了 refs 的其余功能。
下面还包括我根据 Ankh 的回答进行的实验
describe.only("joi features", () => {
const minMax = {
min: Joi.number().less(Joi.ref("max")),
max: Joi.number(),
deep: {
min: Joi.number().less(Joi.ref("max")),
max: Joi.number().required()
},
minOfAll: Joi.number().less(Joi.ref("max")).less(Joi.ref("deep.max"))
};
it("handles max and min relationships", () => {
expect(Joi.validate({ min: 0, max: 99 }, minMax).error).to.not.exist;
expect(Joi.validate({ deep: { min: 0, max: 99 } }, minMax).error).to.not.exist;
expect(Joi.validate({ min: 99, max: 0 }, minMax).error).to.exist;
expect(Joi.validate({ deep: { min: 99, max: 0 } }, minMax).error).to.exist;
expect(Joi.validate({ deep: { max: 99 }, max: 99, minOfAll: 88 }, minMax).error).to.not.exist;
expect(Joi.validate({ deep: { max: 25 }, max: 99, minOfAll: 88 }, minMax).error).to.exist;
expect(Joi.validate({ deep: { max: 99 }, max: 25, minOfAll: 88 }, minMax).error).to.exist;
});
});
【问题讨论】:
标签: validation joi