节点AJV验证模式

时间:2018-05-10 17:56:17

标签: node.js jsonschema json-schema-validator ajv

使用6.5版

我的问题是我有一个请求对象,该对象必须包含一个属性,并且应该包含属性列表中的一个且只有一个其他属性或者这些指定属性都不包含。我已经做了一些挖掘,并且无法找到解决此问题的方法。

可能的有效请求:

{ 'query': {...}, 'limit': 1 }
{ 'query': {...}, 'count': true }
{ 'query': {...}, 'max': 'my_string' }

无效请求将是:

{ 'query': {...}, 'limit': 1, 'count': true }

{ 'query': {...}, 'max': 'my_string', limit: 1 }

我提出的最好的ajv验证器对象如下:

{
    "type": "object",
    "required": ["query"],
    "maxProperties": 2,
    "properties": {
        "query": {
            "type": "object"
        },
        "limit": {
            "type": "integer"
        },
        "count": {
            "type": "boolean"
        },
                "max": {
                        "type": "string"
                }
    }
}

但我知道随着我们的应用程序的增长,这不会扩展。我想知道是否有办法指定对象需要“查询”和“限制”,“计数”,“最大

中的一个或一个

1 个答案:

答案 0 :(得分:1)

找到一种方法来完成我正在寻找的东西。这可以使用"依赖"验证器:

"dependencies": {
    "limit": { "properties": 
        { 
            "count": { "not": {} },
            "max": { "not": {} }
        }
    },
    "count": { "properties": 
        { 
            "limit": { "not": {} },
            "max": { "not": {} }
        }
    },
    "max": { "properties": 
        { 
            "limit": { "not": {} },
            "count": { "not": {} }
        }
    }
}

如果有人知道更好的方式,我很想知道!