如何使用 json 模式验证字符串和数字

How to validate string and number using json schema

我想根据 maximum/minimum(数字)或 maximumLength/minimumLength(字符串)验证模式。 我有一个 json 表格:

[
  {
    "key":"foo",  
    "title":"Test",
    "type":"string" 
  }
]

和一个json架构:

    {
 "type": "object",
  "properties": {
    "foo": {
        "type": ["number","string"],
        "maxLength":2,
        "minLength":0,
        "minimum":3,
        "maximum":10
    }
  }
}

和一个 json 模型:

{
  "foo": "bar"
}

为什么 this example not work with validation? The model I have is not validated to false. According to this document 可以在数组中定义不同的类型,但我们如何根据 min/max 值进行验证?

您的架构正在验证 JSON 个对象 ("type":"object")。此外,如果他们有一个 属性 和键 "foo",它的值必须是 3 到 10 之间的数字,或者最大长度为 2 的字符串。

根据您的架构的有效对象:

{"foo":6}
{"foo":"as"}

无效对象:

{"foo":60}
{"foo":"asereje"}

如果您想验证数组,您必须将父对象定义为数组并使用 items 标记指定数组项的架构,例如:

{
    "type" : "array",
    "items" : {
        "type" : "object",
        "properties" : {
            "foo" : {
                "type" : ["number", "string"],
                "maxLength" : 2,
                "minLength" : 0,
                "minimum" : 3,
                "maximum" : 10
            }
        }
    }
}

上面的架构将验证以下 JSON 数组:

[{
        "foo" : 6
    }, {
        "foo" : "as"
    }
]

您的架构是正确的。您使用的验证器无法正常工作。这是使用 anyOf 的替代方法。

{
    "type": "object",
    "properties": {
        "foo": {
            "anyOf": [
                { "$ref": "#/definitions/boundedNumber" }
                { "$ref": "#/definitions/boundedString" }
            ]
        }
    },
    "definitions": {
        "boundedString": {
            "type": "string",
            "maxLength": 2,
            "minLength": 0
        },
        "boundedNumber": {
            "type": "number",
            "minimum": 3,
            "maximum": 10
        }
    }
}

虽然它有点长,但有些人会争辩说这实际上更容易 read/maintain 因为类型特定关键字的分离。

John 问题是类型 "type" : ["number", "string"]

Angular 模式表单从组合的 JSON 模式和 UI 模式(表单)生成字段,当定义字段类型时,它知道要验证哪种类型,当有多种类型时,它不知道表单字段基于规范的哪一部分,因此它退回到文本框并且不单独为字符串添加适当的验证要求。

为了达到您想要的结果,您需要告诉它您希望使用哪种字段类型。 0.8.x 版本中存在一个错误,如果它无法确定数据模式中的类型,它不会根据 UI 模式中设置的类型进行验证,我相信这已在最新的发展分支。如果不是 Git 中提出的问题,我会优先处理它。