表达字段之间关系的 Joi 模式验证
Joi schema validation that expresses relationships between fields
有没有一种方法可以使用 Joi 表达数据内的关系?
例如
const schema = ({
min: number(),
max: number(),
});
我可以添加一个验证规则 data.min < data.max
吗?
编辑:添加示例
Ankh 的示例真正帮助了我,因为文档有点精简。 Joi tests for ref 帮助实现了 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;
});
});
当然有办法,你会想看看Joi.ref()
。您可以使用它来引用同一 Joi 模式中的参数。
const schema = Joi.object({
min: Joi.number().less(Joi.ref('max')).required(),
max: Joi.number().required()
});
此模式确保 min
和 max
字段都是整数并且是必需的,其中 min
必须小于 max
的值。
有没有一种方法可以使用 Joi 表达数据内的关系?
例如
const schema = ({
min: number(),
max: number(),
});
我可以添加一个验证规则 data.min < data.max
吗?
编辑:添加示例
Ankh 的示例真正帮助了我,因为文档有点精简。 Joi tests for ref 帮助实现了 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;
});
});
当然有办法,你会想看看Joi.ref()
。您可以使用它来引用同一 Joi 模式中的参数。
const schema = Joi.object({
min: Joi.number().less(Joi.ref('max')).required(),
max: Joi.number().required()
});
此模式确保 min
和 max
字段都是整数并且是必需的,其中 min
必须小于 max
的值。