JSON模式验证oneOf two或allOf

时间:2017-01-18 10:51:55

标签: json node.js ajv

我想验证以下json架构,我正在使用Ajv npm包。

{
    "email": "xyzmail@gmail.com",
    "phone": "1112223334",
    "country_code": "91"
}

我只想要电子邮件,或仅手机和country_code ,或者 ll of three 属性。

我已经尝试过oneOf,allOf,anyOf也尝试过嵌套主题但在某些情况下它的工作和某些条件不起作用。

我试过以下代码

{
    "type": "object",
    "properties": {
        "email": {
            "type": "string",
            "format": "email",
            "maxLength": constants.LENGTHS.EMAIL.MAX
        },
        "phone": {
            "type": "string",
            "pattern": constants.REGEX.PHONE,
            "maxLength": constants.LENGTHS.PHONE.MAX
        },
        "country_code": {
            "type": "string",
            "pattern": constants.REGEX.COUNTRY_CODE,
            "maxLength": constants.LENGTHS.COUNTRY_CODE.MAX
        }
    },
    "anyOf": [
        {
            "required": ["email"],
        },
        {
            "required": ["phone", "country_code"],
        },
        {
            "required": ["email", "phone", "country_code"]
        },
    ],
    "additionalProperties": false

}

1 个答案:

答案 0 :(得分:2)

你需要:

"anyOf": [
    {
        "required": ["phone", "country_code"]
    },
    {
        "required": ["email"],
        "not": {
            "anyOf": [
                { "required": ["phone"] },
                { "required": ["country_code"] }
            ]
        }
    }
]

第一个子架构允许存在和不存在的电子邮件,这就是你想要的。

使用关键字" propertyNames"添加到JSON-schema draft-06的关键字(即将发布,在Ajv 5.0.1-beta中提供),您可以使它更简单(更容易阅读):

"anyOf": [
    {
        "required": ["phone", "country_code"]
    },
    {
        "required": ["email"],
        "propertyNames": {"not": {"enum": ["phone", "country_code"] } }
    }
]

或者您可以使用自定义关键字"禁止"在ajv-keywords中定义(参见https://github.com/json-schema-org/json-schema-spec/issues/213):

"anyOf": [
    {
        "required": ["phone", "country_code"]
    },
    {
        "required": ["email"],
        "prohibited": ["phone", "country_code"]
    }
]