Home > Mobile >  Node Js Joi validate object that contains list of same object
Node Js Joi validate object that contains list of same object

Time:07-22

Suppose I have the following object represented in json:

{
  "name": "Joe",
  "childrens": [
    {
      "name": "Marie",
      "childrens": [
        {
          "name": "Paul"
        }
      ]
    },
    {
      "name": "Nick",
      "childrens": [
      ]
    }
  ]
}

How can I create a schema to validate an object that contains a list of the same object?

CodePudding user response:

You can use the Joi.lazy() method to implement a recursive schema like:

const Person = Joi.object({
  name: joi.string().required(),
  children: joi.array().items(joi.lazy(() => Person).description('My Schema'))
});

In newer versions of Joi you have to use Joi.link() in order to link an id of a schema.

const personSchema = joi
  .object({
    name: joi.string().required(),
    children: joi.array().items(joi.link("#person"))
  })
  .id("person");

Note I renamed your childrens property to children.

  • Related