繁体   English   中英

JSON 模式验证 oneOf 两个或 allOf

[英]JSON schema validate oneOf two or allOf

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

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

我只想要电子邮件,或者只想要电话和国家代码,或者三个属性中的所有属性都应该在那里。

我尝试过 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"] }
            ]
        }
    }
]

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

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

"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"]
    }
]

暂无
暂无

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

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