22

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.

ankit kothana
  • 661
  • 1
  • 5
  • 6

2 Answers2

42

Resolved the issue by using:

var innerArraySchema = {
"type": "array",
"items" : innerSchema
}
ankit kothana
  • 661
  • 1
  • 5
  • 6
0

It's $ref not #ref.

Also note that you can load a schema by ID:

var innerArraySchema = {
  "type": "array",
  "items": {
    $ref: 'https://www.example.com/my-schema.schema.json',
  },
  "items" : innerSchema
}

Note that using a schema ID (URL) in this way will NOT cause the schema to be imported automatically; you will need to use Ajv.getSchema() or Ajv.addSchema() to load the schema, too.

There's more info in the docs on combining schemas.

Patrick Kenny
  • 4,515
  • 7
  • 47
  • 76