【问题标题】:JSON schema validate oneOf two or allOfJSON 模式验证 oneOf 两个或 allOf
【发布时间】:2017-06-02 17:09:12
【问题描述】:

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

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

我只想要 email,或者只想要 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

}

【问题讨论】:

    标签: json node.js ajv


    【解决方案1】:

    你需要:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-03
    • 1970-01-01
    • 2022-06-11
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    • 2022-01-14
    • 2014-05-06
    相关资源
    最近更新 更多