表达字段之间关系的 Joi 模式验证

Ash*_*man 4 validation joi

有没有办法使用 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)

Ank*_*nkh 7

当然有一种方法,您会想检查一下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)

此架构确保minmax字段都是整数,并且min必须小于 的值max