对象数组的AJV模式验证 [英] AJV schema validation for array of objects

查看:358
本文介绍了对象数组的AJV模式验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用AJV模式验证来验证对象数组。以下是示例代码

I am trying to validate array of objects using AJV schema validation. Below is the sample code

var Ajv = require('ajv');
var schemaValidator = Ajv();

var innerSchema = {
"type" : "object",
"properties" : {
    "c" :  {
        "type" : "string"
    },
    "d" : {
        "type" : "number"
    }
},
"required" : ["c"]
}

var innerArraySchema = {
"type": "array",
"items" : {
    "#ref": innerSchema
}
}

var schema = {
"type" : "object",
"properties" : {
    "a" :  {
        "type" : "string"
    },
    "b" : {
        "type" : "string"
    },
    "obj" : innerArraySchema
},
"required" : ["a"]
}

var testSchemaValidator = schemaValidator.compile(schema);

var data = {"a": "123","b" : "abc", "obj" : [{
"d" : "ankit"
}]}


var valid = testSchemaValidator(data);

console.log(valid);

if(!valid) {
    console.log(testSchemaValidator.errors);
}

我在这里缺少什么东西。我不想在数组定义本身中添加属性对象。

Is there something that I am missing here. I would not like to add the properties object inside the array definition itself.

推荐答案

使用以下方法解决了这个问题:

Resolved the issue by using:

var innerArraySchema = {
"type": "array",
"items" : innerSchema
}

这篇关于对象数组的AJV模式验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆