【问题标题】:Joi schema validation that expresses relationships between fields表示字段之间关系的 Joi 模式验证
【发布时间】:2017-05-31 01:43:06
【问题描述】:

有没有办法使用 Joi 来表达数据中的关系?

例如

  const schema = ({
    min: number(),
    max: number(),
  });

我可以添加一条验证规则,上面写着data.min < data.max吗?

编辑:添加示例

Ankh 的示例对我很有帮助,因为文档有点精简。 Joi tests for ref 帮助了 refs 的其余功能。

下面还包括我根据 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;
  });
});

【问题讨论】:

    标签: validation joi


    【解决方案1】:

    当然有办法,您可以查看Joi.ref()。您可以使用它来引用同一 Joi 架构中的参数。

    const schema = Joi.object({
        min: Joi.number().less(Joi.ref('max')).required(),
        max: Joi.number().required()
    });
    

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

    【讨论】:

      猜你喜欢
      • 2019-05-01
      • 2016-05-08
      • 2016-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多