Json 基于数据的ajv条件模式验证
我想根据另一个字段中的数据为一个字段指定一个regexp模式。这可能吗?我试过switch和$data,但不知道如何使用它们。 例如,如果数据如下所示:Json 基于数据的ajv条件模式验证,json,schema,ajv,Json,Schema,Ajv,我想根据另一个字段中的数据为一个字段指定一个regexp模式。这可能吗?我试过switch和$data,但不知道如何使用它们。 例如,如果数据如下所示: { "contacts":[ { "mode":"Email", "contact":"john.doe@abc.com" }, { "mode":"Phone", "contact":"111-555-1234" }
{
"contacts":[
{
"mode":"Email",
"contact":"john.doe@abc.com"
},
{
"mode":"Phone",
"contact":"111-555-1234"
}
]
}
模式类似于:
"$schema":"http://json-schema.org/draft-04/schema#",
"type":"object",
"properties":{
"Contacts":{
"type":"array",
"minItems":1,
"items":{
"type":"object",
"properties":{
"mode":{
"type":"string",
"enum":[
"Email",
"Phone"
]
},
"contact":{
"type":"string",
"pattern":"?????"
}
},
"required":[
"mode",
"contact"
]
}
}
}
}
如何根据模式中的数据设置联系人模式,以便如果模式为电子邮件,则针对电子邮件格式的regexp验证联系人,如果模式为电话,则针对电话格式的regexp验证联系人?我有每个的regexp。我需要逻辑来选择其中一个。有几种方法 anyOf(优点:草稿-04兼容,缺点:错误报告有点冗长-如果两个子模式都不匹配,您将从中得到错误): if/then/else(,优点:错误报告更有意义,缺点:目前不标准): 选择(,优点:比if/then/else更简洁,特别是如果有两个以上的可能值,缺点:,但您可以支持:),需要启用$data reference和Ajv v5.x.x):
我更喜欢最后一个选项。非常有趣。基于其中一个属性的值,您将如何处理动态所需属性?无需担心,我明白了,这要感谢AJV令人敬畏的灵活性。
{
"type": "object",
"properties": {
"Contacts": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"anyOf": [
{
"properties": {
"mode": {"enum": ["Email"]},
"contact": {
"type": "string",
"format": "email"
}
}
},
{
"properties": {
"mode": {"enum": ["Phone"]},
"contact": {
"type": "string",
"pattern": "phone_pattern"
}
}
}
],
"required": ["mode", "contact"]
}
}
}
}
{
"type": "object",
"properties": {
"Contacts": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"properties": {
"mode": {"type": "string", "enum": ["Email", "Phone"]},
"contact": {"type": "string"}
},
"if": {
"properties": {
"mode": {"enum": ["Email"]}
}
},
"then": {
"properties": {
"contact": {"format": "email"}
}
},
"else": {
"properties": {
"contact": {"pattern": "phone_pattern"}
}
}
"required": ["mode", "contact"]
}
}
}
}
{
"type": "object",
"properties": {
"Contacts": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"properties": {
"mode": {"type": "string"},
"contact": {"type": "string"}
},
"select": { "$data": "0/mode" },
"selectCases": {
"Email": {
"properties": {
"contact": {"format": "email"}
}
},
"Phone": {
"properties": {
"contact": {"pattern": "phone_pattern"}
}
}
},
"selectDefault": false,
"required": ["mode", "contact"]
}
}
}
}