Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joi schema validation that expresses relationships between fields

Tags:

validation

joi

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;
  });
});
like image 862
Ashley Coolman Avatar asked Sep 12 '25 06:09

Ashley Coolman


1 Answers

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.

like image 111
Ankh Avatar answered Sep 15 '25 03:09

Ankh