Joi schema validation that expresses relationships between fields

Viewed 1153

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?

EDIT: Adding examples

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 refs 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;
  });
});
1 Answers
Related