简体   繁体   English

JS Json模式-AJV

[英]JS Json Schema - AJV

I'm using AJV (JS JSON Schema Validator), and I'm trying to find a way to extend the types it supports. 我正在使用AJV(JS JSON架构验证器),并且试图找到一种扩展其支持的类型的方法。

I'm getting this error because In the schema I have a custom type (DocumentReference that I'm validating in python - jsonschema as well) 我收到此错误的原因是,在架构中,我有一个自定义类型(我也在python中验证的DocumentReference-jsonschema)

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)

This is a small sample of the schema: 这是模式的一小部分示例:

"custom_signature": {
    "type": [
        "DocumentReference",
        "object",
        "null"
    ]
},

In python jsonschema there is a way to extend the types and define how you want to validate them, is there some equivalent in AJV? 在python jsonschema中,有一种方法可以扩展类型并定义要如何验证它们,AJV中是否有等效的方法?

 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': {}})); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/6.4.0/ajv.min.js"></script> 

JSFiddle JSFiddle

I just made a module to simplify some AJV issues. 我只是制作了一个模块来简化一些AJV问题。 It also includes a new function called .addType(): 它还包括一个名为.addType()的新函数:

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

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

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' }
  }
}

You can also: 你也可以:

const schema = {
  properties: {
    '*name': 'string',
    '*email': 'email',
    'age': 'number',
    '*message': 'string',
  }
}

Enjoy! 请享用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM