有没有办法使用 Joi 表达数据内的关系?
例如
const schema = ({
min: number(),
max: number(),
});
Run Code Online (Sandbox Code Playgroud)
我可以添加一条验证规则吗data.min < data.max
?
Ankh 的例子确实对我有帮助,因为文档有点精简。ref 的 Joi 测试对s的其余ref
功能有帮助。
下面还包括我根据 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;
});
});
Run Code Online (Sandbox Code Playgroud)
当然有一种方法,您会想检查一下Joi.ref()
。您可以使用它来引用同一 Joi 模式中的参数。
const schema = Joi.object({
min: Joi.number().less(Joi.ref('max')).required(),
max: Joi.number().required()
});
Run Code Online (Sandbox Code Playgroud)
此架构确保min
和max
字段都是整数,并且min
必须小于 的值max
。
归档时间: |
|
查看次数: |
1426 次 |
最近记录: |