NodeJS JSON schema if/else/then不能正常工作

fzsnzjdm  于 2023-06-29  发布在  Node.js
关注(0)|答案(1)|浏览(162)

我有一个用例,基于一个属性,我想验证一个正则表达式模式上的对象的键,如果不匹配,则验证另一个正则表达式属性。现在对于中定义的特定const值,如果它确实选择了then的正则表达式,但对于其他值,它没有选择else条件。我正在使用AJV验证。
我的模式看起来像这样->

"properties": {
  "location": {
    "title": "Path",
    "type": "string",
    "description": "The relative JSON path of the location to which the properties should be set",
    "examples": ["abc", "def"],
    "pattern": "^.*$"
  },
  "properties": {
    "title": "Properties",
    "type": "object",
    "description": "The set of properties that shall be set on the given relative path",
    "if": {
      "properties": {
        "propertyType": {
          "const": "123"
        }
      }
    },
    "then": {
      "patternProperties": {
        "^[-&/_.:a-zA-Z0-9]+$": {
          "anyOf": [{
              "type": "string"
            },
            {
              "type": "number"
            },
            {
              "type": "boolean"
            }
          ]
        }
      },
      "additionalProperties": false
    },
    "else": {
      "patternProperties": {
        "^.*$": {
          "anyOf": [{
              "type": "string"
            },
            {
              "type": "number"
            },
            {
              "type": "boolean"
            }
          ]
        }
      },
      "additionalProperties": false
    }
  }
}

然后我在这里有一个特定的正则表达式,如果propertyType值为123,则不允许空格,如果不是123,则允许空格。
现在,对于这个数据,它确实不允许空格,并且验证失败。->

{
  "type" : "xyz",
  "anchor" : {
  "propertyType : "123"
},
setProperties : {
  "random_123 " : "value1"
}
}

但是,即使propertyType不是123,它也会在相同的then验证中失败。

{
  "type" : "xyz",
  "anchor" : {
   "propertyType : "456"
},
setProperties : {
  "random_123 " : "value1"
}
}

我能做错什么?

fnx2tebb

fnx2tebb1#

你的样品看起来很混乱。但我认为你只是混淆了应用条件和patternProperties的验证级别。下面的简化模式工作正常:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "if": {
    "properties": {
      "propertyType": {
        "const": "123"
      }
    }
  },
  "then": {
    "patternProperties": {
      "^[-&/_.:a-zA-Z0-9]+$": {
        "anyOf": [
          { "type": "string" },
          { "type": "number" },
          { "type": "boolean" }
        ]
      }
    },
    "additionalProperties": false
  },
  "else": {
    "patternProperties": {
      "^.*$": {
        "anyOf": [
          { "type": "string" },
          { "type": "number" },
          { "type": "boolean" }
        ]
      }
    },
    "additionalProperties": false
  }
}

这个JSON是有效的:

{
    "propertyType": "123",
    "foobar": "baz"
}

这一个是无效的:

{
    "propertyType": "123",
    "foo@bar": "baz"
}

相关问题