验证架构

问题描述 投票:0回答:2

我们如何验证书面架构是否有效。

const schema = {
  "properties": {
    "foo": { "add": "string" , "minLenfeffgth": 3, "maxLefngth": 255 }
  }
};

根据ajv.validateSchema(),上面提到的模式是有效的模式。

就像我们验证数据一样,有任何函数可以验证模式。

完整代码:

var Ajv = require('ajv');

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

const schema = {
  "properties": {
    "foo": { "add": "string" , "minLenfeffgth": 3, "maxLefngth": 255 }
  }
};

// console.log(ajv.validateSchema(schema));
var validate = ajv.compile(schema);

test({"foo": ""});

function test(data) {
  var valid = validate(data);
  if (valid) console.log('Valid!');
  else console.log(validate.errors);
}

结果是:有效

node.js json-schema-validator ajv
2个回答
0
投票

您可以配置Ajv以抛出错误并使用compile

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

var schema = {
  type: 'object',
  properties: {
    date: {
      type: 'unexisting-type'
    }
  }
};

try {
  var validate = ajv.compile(schema);
} catch (e) {
  console.log(e.message);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/6.6.2/ajv.min.js"></script>

0
投票

上面提到的模式是根据ajv.validateSchema()的有效模式。

它是有效的,但它没有验证,如果你想用foo强制属性测试一个简单的对象,你可以这样做:

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

var schema = {
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "foo": {
      "type": "string",
      "minLength": 3,
      "maxLength": 255
    }
  },
  "required": [
    "foo"
  ]
};

try {
  var validate = ajv.compile(schema);
  test({"foo": "" });
} catch (e) {
  console.log("Validate error :" + e.message);
}


function test(data) {
  var valid = validate(data);
  if (valid) {
    console.log('Valid!');
  } else {
    console.log(validate.errors);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/6.6.2/ajv.min.js"></script>

使用data = {"foo": "" }运行时返回以下错误消息:

[
  {
    "keyword": "minLength",
    "dataPath": ".foo",
    "schemaPath": "#/properties/foo/minLength",
    "params": {
      "limit": 3
    },
    "message": "should NOT be shorter than 3 characters"
  }
]

使用data = {"foo": "abcdef" }运行时返回以下消息:

有效!

© www.soinside.com 2019 - 2024. All rights reserved.