我想验证以下 json 架构,我正在使用 Ajv npm 包。
{
"email": "xyzmail@gmail.com",
"phone": "1112223334",
"country_code": "91"
}
Run Code Online (Sandbox Code Playgroud)
我想要仅电子邮件,或仅电话和国家/地区代码,或者所有三个属性都应该在那里。
我已经尝试过 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
}
Run Code Online (Sandbox Code Playgroud)
你需要:
"anyOf": [
{
"required": ["phone", "country_code"]
},
{
"required": ["email"],
"not": {
"anyOf": [
{ "required": ["phone"] },
{ "required": ["country_code"] }
]
}
}
]
Run Code Online (Sandbox Code Playgroud)
第一个子模式允许电子邮件存在和不存在,这正是您想要的。
使用添加到 JSON 模式草案 06(即将发布,在 Ajv 5.0.1-beta 中提供)中的关键字“propertyNames”关键字,您可以使其变得更简单(并且更易于阅读):
"anyOf": [
{
"required": ["phone", "country_code"]
},
{
"required": ["email"],
"propertyNames": {"not": {"enum": ["phone", "country_code"] } }
}
]
Run Code Online (Sandbox Code Playgroud)
或者您可以使用ajv-keywords中定义的自定义关键字“prohibited” (请参阅 https://github.com/json-schema-org/json-schema-spec/issues/213):
"anyOf": [
{
"required": ["phone", "country_code"]
},
{
"required": ["email"],
"prohibited": ["phone", "country_code"]
}
]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9232 次 |
| 最近记录: |