Is there a way to express relationships within the data using Joi?
e.g.
const schema = ({
min: number(),
max: number(),
});
Could I add a validation rule that says data.min < data.max
?
Ankh's example is what really helped me as the docs are a bit lean. The Joi tests for ref helped with the rest of ref
s features.
Also included below is my experiment based off Ankh's answer
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;
});
});
There certainly is a way, you'll want to check out Joi.ref()
. You can use it to reference parameters within the same Joi schema.
const schema = Joi.object({
min: Joi.number().less(Joi.ref('max')).required(),
max: Joi.number().required()
});
This schema ensures both min
and max
fields are integer and required where min
must be less than the value of max
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With