JSON schema 验证 oneOf two 或 allOf

JSON schema validate oneOf two or allOf

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

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

我只想要电子邮件,或者只想要phone和country_code,或者应该有三个 个属性。

我试过 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

}

你需要:

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

第一个 sub-schema 允许存在和不存在的电子邮件,这正是您想要的。

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

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

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

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