无法使用IS-MY-JSON-VALID NPM模块正确验证对象数组



我正在使用is-my-json-valid npm模块来验证传入的HTTP请求。我定义了模式以验证对象数组。此NPM模块无法正确验证数组中的对象。

我已经定义了如下所述的架构:

var validator = require('is-my-json-valid')

var validate = validator({
    required: true,
    type: 'object',
    properties: {
        name: {
            required: true,
            type: 'string'
        },
        author: {
            required: true,
            type: 'string'
        },
        libraries: {
            required: true,
            type: 'array',
            items: {
                type: 'object',
                properties: {
                    id: {
                        required: true,
                        type: 'number'
                    }
                },
                additionalProperties: false
            }
        }
    },
    additionalProperties: false
});
const obj = {
    name: 'myn4m3',
    author: 'mys3lf',
    libraries: []
};
console.log('should be valid', validate(obj));
// console.log('should not be valid', validate({}))
console.log(validate.errors) 

实际:应该有效null

期望:由于库数组具有强制性的" ID"属性,因为我不提供它应该丢弃验证错误,但它给出了True。

有人可以为此提供帮助吗?

您需要在数组中添加对象

更改此

const obj = {
name: 'myn4m3',
author: 'mys3lf',
libraries: []

};

到这个

const obj = {
name: 'myn4m3',
author: 'mys3lf',
libraries: [{}]

};

最新更新