JSON模式验证oneOf两个或allOf [英] JSON schema validate oneOf two or allOf
问题描述
我要验证以下json模式,我使用的是Ajv npm软件包.
i want to validate following json schema, i am using Ajv npm package.
{
"email": "xyzmail@gmail.com",
"phone": "1112223334",
"country_code": "91"
}
我只希望电子邮件,或者仅电话和国家/地区代码,或者应该有三个所有属性.
i want either email only, or phone and country_code only, or all of three properties should be there.
我尝试过oneOf,allOf,anyOf也尝试过嵌套主题,但是在某些情况下它可以工作,在某些情况下它不能工作.
i have tried oneOf, allOf, anyOf also have tried nested of theme but in some conditions its working and in some condidions its not working.
我尝试了以下代码
{
"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"] }
]
}
}
]
第一个子模式允许存在和不存在的电子邮件,这就是您想要的.
The first sub-schema allows for email both present and absent, which is what you want.
使用添加到JSON模式-06草稿(即将发布,将在Ajv 5.0.1-beta中提供)的关键字"propertyNames"关键字,您可以使其更简单(更易于阅读):>
Using keyword "propertyNames" keyword that is added to JSON-schema draft-06 (to be published soon, available in Ajv 5.0.1-beta) you can make it a bit simpler (and easier to read):
"anyOf": [
{
"required": ["phone", "country_code"]
},
{
"required": ["email"],
"propertyNames": {"not": {"enum": ["phone", "country_code"] } }
}
]
或者您可以使用 ajv-关键字(参见 https://github.com/json-schema-org /json-schema-spec/issues/213 ):
Or you can use custom keyword "prohibited" defined in ajv-keywords (see https://github.com/json-schema-org/json-schema-spec/issues/213):
"anyOf": [
{
"required": ["phone", "country_code"]
},
{
"required": ["email"],
"prohibited": ["phone", "country_code"]
}
]
这篇关于JSON模式验证oneOf两个或allOf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!