2

我已经编写了一个模式,但它似乎并没有像我预期的那样进行验证。我假设我的模式语法有问题,但无法弄清楚。我希望在筹款活动完成之前不会看到标题或目标的错误消息,因为只有在筹款活动完成时才需要它们。我尝试了很多组合,但没有一个按预期工作,这两个是我最接近我需要的。

模式尝试一:显示 4 条错误消息、3 条必需错误和 1 条错误,说明数据应与“then”模式匹配。

const schema = {
  required: ['fundraiser'],
  if: {
    properties: {
      fundraiser: { type: 'string' },
    },
  },
  then: {
    required: ['title', 'target'],
  },
  errorMessage: {
    required: {
      fundraiser: 'Please select an option',
      title: 'Please enter a title',
      target: 'Please enter a target',
    },
  },
};

模式尝试二:显示 2 条错误消息,1 条必需的错误和 1 条错误说数据应该匹配正确的“then”模式,但是当我完成筹款活动时,有效变为真,这是我希望看到标题和目标所需的错误的时候。我定义的自定义错误消息也没有错误。

const scema = {
  if: {
    properties: { fundraiser: { minLength: 2 } },
    then: { required: ['title', 'target'] },
  },
  then: { required: ['fundraiser'] },
  errorMessage: {
    required: {
      fundraiser: 'Please select an option',
      title: 'Please enter a title',
      target: 'Please enter a target',
    },
  },
};

我很确定我的架构有问题,但是从文档中不清楚如何使用 if/then 与使用 ajv-errors 的自定义错误消息结合使用。任何帮助将不胜感激!谢谢!

4

1 回答 1

1

第一个模式的问题是“if”中的子模式是有效的,除非存在筹款人属性而不是字符串。type: 'object'如果您添加到根模式并移动required到“if”子模式中,它可能会按您的预期工作。

第二个子模式的问题是,在同一个模式对象中没有“if”的第一个“then”被忽略(除非您使用的 ajv-keywords 实现 if/then/else 的方式与草案中的定义略有不同JSON Schema 规范的 -07)和“if is valid即使fundraiser属性不存在也是有效的,第二个“then”只有在fundraiser存在时才能通过。

于 2017-12-05T20:14:13.780 回答