AJV:检查一个属性是否等于另一个属性

DKo*_*DKo 1 node.js ajv

通过使用ajv,我如何引用foo验证bar具有相同的值?

var Ajv = require('ajv');
var ajv = new Ajv({allErrors: true});

var schema = {
  'properties': {
    'foo': { 'type': 'string', 'minLength': 3 },
    'bar': { 'type': 'string', ###HERE### },
  }
};

data = {
  'foo': 'abc',
  'bar': 'ab',
};

ajv.validate(schema, data);   // <-- should return false, foo !== bar
Run Code Online (Sandbox Code Playgroud)

我试过使用(有类似的变化):

...
'bar': { 'type': 'string', 'format': { '$data': 'foo' } },
...
Run Code Online (Sandbox Code Playgroud)

但这没有用。

esp*_*esp 7

你可以:

var ajv = new Ajv({allErrors: true, $data: true}); // for version >=5.0.0

var schema = {
  properties: {
    foo: { type: 'string', minLength: 3 },
    bar: { const: { $data: '1/foo' } },
  }
};
Run Code Online (Sandbox Code Playgroud)

  • @alayor - 已经有一段时间了,但是 `1/` 基本上意味着“上一层并检查属性”。 (2认同)