如何使用ajv验证数组的项目?

时间:2019-08-01 02:00:20

标签: validation jsonschema ajv

我的验证器定义如下

var abcSchemaValidator = {
"type": "object",
"required": [],
"properties": {
    "remarks": {
        "type": "string",
        "maxLength": 2000
    },
    "comment": {
        "type": "string",
        "maxLength": 2000
    }
}
};

在我要应用这些验证的代码中,我正在做类似的事情

modelObject.remarks = sometext;

modelObject.parent[0].comment

因此,当我使用以下代码运行ajv验证

let validate = ajv.compile(schema);
let validResult = validate(data);

评论正确验证,而注释未正确验证。我可以看到为什么言论很简单,但是我不确定如何使评论生效。我应该在schemaValidator中将注释更改为parent.comment吗?我尝试更改为parent [0] .comment,但是没有用。

1 个答案:

答案 0 :(得分:1)

您的架构没有为parent定义任何规则,也没有禁止其他属性。正如您的架构按预期那样工作。

据我所知,parent是:

  1. 对象的非必需但预期的属性
  2. 对象数组,每个对象都可以具有comment属性,该属性与remarks相同

首先,让我们定义一些我们可以重复使用的东西:

ajv.addSchema({
  $id: 'defs.json',
  definitions: {
    userInput: {
      type: 'string',
      maxLength: 10
    }
  }
});

然后,让我们使用此通用定义重新定义remarks并定义parent

const validate = ajv.compile({
  $id: 'main.json',
  type: 'object',
  properties: {
    remarks: {$ref: 'defs.json#/definitions/userInput'},
    parent: {
      type: 'array',
      items: {
        type: 'object',
        properties: {
          comment: {$ref: 'defs.json#/definitions/userInput'}
        }
      }
    }
  }
});

现在让我们验证一些数据:

// OK
console.assert(validate({remarks: 'foo'}),
  JSON.stringify(validate.errors, null, 2));

// ERR: `remarks` is too long
console.assert(validate({remarks: 'foobarbazbat'}),
  JSON.stringify(validate.errors, null, 2));

// OK: schema doesn't say `parent` can't be empty
console.assert(validate({remarks: 'foo', parent: []}),
  JSON.stringify(validate.errors, null, 2));

// OK: schema doesn't say `parent` elements MUST have a `comment` property
console.assert(validate({remarks: 'foo', parent: [{}]}),
  JSON.stringify(validate.errors, null, 2));

// OK
console.assert(validate({remarks: 'foo', parent: [{comment: 'foo'}]}),
  JSON.stringify(validate.errors, null, 2));

// ERR: `comment` is too long
console.assert(validate({remarks: 'foo', parent: [{comment: 'foobarbazbat'}]}),
  JSON.stringify(validate.errors, null, 2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/6.10.2/ajv.min.js"></script>
<script>
const ajv = new Ajv();

ajv.addSchema({
  $id: 'defs.json',
  definitions: {
    userInput: {
      type: 'string',
      maxLength: 10
    }
  }
});

const validate = ajv.compile({
  $id: 'main.json',
  type: 'object',
  properties: {
    remarks: {$ref: 'defs.json#/definitions/userInput'},
    parent: {
      type: 'array',
      items: {
        type: 'object',
        properties: {
          comment: {$ref: 'defs.json#/definitions/userInput'}
        }
      }
    }
  }
});
</script>