简体   繁体   English

TV4 JSON Schema对象数组验证

[英]TV4 JSON Schema array of objects validation

I would like to validate that a property called "foo" contains an array of "bar" objects. 我想验证一个名为“ foo”的属性是否包含“ bar”对象的数组。

Using TV4 for validation all works as expected if I use an array as the value of foo however if I specify something other than an array such as a string or an integer validation passes when it should not. 如果我使用数组作为foo的值,那么使用TV4进行验证将按预期工作,但是如果我指定了非数组的值(例如字符串或整数验证),则该方法应按预期进行。

var json = { "foo" : { "one" : "bar" }};

Passes as expected with a correctly formatted array. 按预期通过格式正确的数组。

var json = { "foo" : { "bar" : "error" }};

Fails as expected with in-correct formatted array. 使用格式不正确的数组,按预期失败。

var json = { "foo" : 2 };

Passes event though foo should be an array. 通过事件,尽管foo应该是一个数组。

Below is the full code. 下面是完整的代码。

var should = require("should");
var validator = require("tv4");

var barSchema = {
    "id": "bar",
    "type" : "object",
    "properties": {
        "one": {
            "type": "string"
        }
    },
    "required": ["one"],
    "additionalProperties": false
}

var fooSchema = {
    "id" : "foo",
    "title": "foo",
    "type": "object",
    "properties": {
        "foo" : {
            "type:" : "array",
            "items": {"$ref":"bar"}
        }
    },
    "required": [
        "foo"
    ]
}

describe("foo with integer", function() {
    it("should result in an error message", function(){
        var json = {
            "foo" : 2
        }
        validator.addSchema(barSchema);
        var result = validator.validate(json, fooSchema);

        // above should fail but it passes
    });
}); 

I think you missed to add fooSchema to the validator: 我认为您错过了将fooSchema添加到验证器的过程:

describe("foo with integer", function() {
    it("should result in an error message", function(){
        var json = {
            "foo" : 2
        }
        validator.addSchema(barSchema);
        validator.addSchema(fooSchema);
        var result = validator.validate(json, fooSchema);

        // above should fail but it passes
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM