首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JS Json架构- AJV

JS Json架构- AJV
EN

Stack Overflow用户
提问于 2018-04-04 19:56:56
回答 1查看 860关注 0票数 1

我正在使用AJV (JS JSON Schema Validator),并试图找到一种方法来扩展它所支持的类型。

我得到这个错误是因为在模式中我有一个自定义类型(我也在python -python模式中验证了DocumentReference)

代码语言:javascript
复制
Error: schema is invalid: data.properties['allow'].properties['custom_signature'].type should be equal to one of the allowed values, data.properties['allow'].properties['custom_signature'].type[0] should be equal to one of the allowed values, data.properties['allow'].properties['custom_signature'].type should match some schema in anyOf
    at Ajv.validateSchema (ajv.js?ea76:183)
    at Ajv._addSchema (ajv.js?ea76:312)
    at Ajv.compile (ajv.js?ea76:112)
    at eval (configs.js?76ed:66)

这是该模式的一个小示例:

代码语言:javascript
复制
"custom_signature": {
    "type": [
        "DocumentReference",
        "object",
        "null"
    ]
},

在python jsonschema中,有一种方法可以扩展类型并定义如何验证它们,在AJV中是否有一些等价物?

代码语言:javascript
复制
var json = {
  "type": "object",
  "properties": {
    "custom_signature": {
      "type": [
        "DocumentReference",
        "null",
        "object"
      ]
    }
  }
};

const ajv = new Ajv({
  allErrors: true
});
console.log(ajv);
const validate = ajv.compile(json);
console.log(validate({'custom_signature': {}}));
代码语言:javascript
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/6.4.0/ajv.min.js"></script>

JSFiddle

EN

回答 1

Stack Overflow用户

发布于 2019-02-23 02:07:13

我刚刚做了一个模块来简化一些AJV问题。它还包括一个名为.addType()的新函数:

Github:https://github.com/webarthur/super-ajv

NPM:https://www.npmjs.com/package/super-ajv

代码语言:javascript
复制
const ajv = new Ajv()

ajv.addType('mongoid', {
  compile: function () {
    return function (data) {
      const re = /^(?=[a-f\d]{24}$)(\d+[a-f]|[a-f]+\d)/i
      return re.test(data)
    }
  }
})

const schema = {
  properties: {
    user_id: { type: 'mongoid' }
  }
}

您还可以:

代码语言:javascript
复制
const schema = {
  properties: {
    '*name': 'string',
    '*email': 'email',
    'age': 'number',
    '*message': 'string',
  }
}

享受吧!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49650391

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档