Json Schema:验证数组

时间:2017-04-29 19:12:50

标签: node.js jsonschema ajv

我正在尝试验证包含两个密钥tagsparameters的模式,这些密钥旨在成为任意键值对的数组。但是出于某些原因,我无法获得我为这两个键指定的任何以使验证失败(我正在使用nodejs库ajv)。

以下是架构定义:

var cfStackSchema = {
  name: { type: "string" },
  application: { type: "string" },
  account: { type: "string" },
  environment: { type: "string" },
  tags: { 
    type: "array",
    items: {
      type: "object",
      patternProperties: {
        "^[a-zA-z0-9]$": { type: "string" }
      },
      additionalProperties: false
    },
    additionalItems: false
  },
  parameters: { 
    type: "array",
    items: {
      type: "object",
      patternProperties: {
        "^[a-zA-z0-9]$": { type: "string" }
      },
      additionalProperties: false
    },
    additionalItems: false
  },
  deps: { type: "array", items: { type: "string" } },
  required: ["name", "account", "environment", "parameters", "application"]
};

这是一个测试对象。我在这里作为一个简单的字符串传递parameters,意图使它失败验证,但实际上它通过了:

var spec = { name: "test", 
            account: "test", 
            environment: "test",
            parameters: "test",
            application: "test"
          };

以下是我用来验证的代码:

  var ajv = new Ajv({ useDefaults: true });
  var validate = ajv.compile(cfStackSchema);
  if (!validate(spec)) {
    throw new Error('Stack does not match schema!')
  }

1 个答案:

答案 0 :(得分:1)

您只需将属性放在properties对象

var cfStackSchema = {
  properties: {
    name: { type: "string" },
    application: { type: "string" },
    account: { type: "string" },
    environment: { type: "string" },
    tags: { 
      type: "array",
      items: {
        type: "object",
        patternProperties: {
          "^[a-zA-z0-9]$": { type: "string" }
        },
        additionalProperties: false
      },
      additionalItems: false
    },
    parameters: { 
      type: "array",
      items: {
        type: "object",
        patternProperties: {
          "^[a-zA-z0-9]$": { type: "string" }
        },
        additionalProperties: false
      },
      additionalItems: false
    },
    deps: { type: "array", items: { type: "string" } },
  },
  required: ["name", "account", "environment", "parameters", "application"]
};