【问题标题】:Validate the schema验证架构
【发布时间】:2019-03-06 12:21:48
【问题描述】:

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

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


    【解决方案1】:

    您可以将 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>
    【解决方案2】:

    上述架构是根据 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"
      }
    ]
    

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

    有效!

    【讨论】:

      猜你喜欢
      • 2010-10-22
      • 2012-05-29
      • 2010-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-23
      相关资源
      最近更新 更多