29

I am trying to create nested schema in joi and it is throwing error

[Error: Object schema cannot be a joi schema]

var nestedSchema = joi.object({
    b: joi.number()
});

var base = joi.object({
    a: joi.string(),
    nestedData:joi.object(nestedSchema)
});

How should i define nested schema in joi?

Anshul
  • 293
  • 1
  • 3
  • 5

5 Answers5

44

Although Francesco's answer works, there's no need to use object.keys(). The error the question creator was doing is to pass a schema as a parameter to joi.object().

So, creating nested schemas is as simple as assigning a schema to a key belonging to another schema.

const schemaA = Joi.string()
const schemaB = Joi.object({ keyB1: schemaA, keyB2: Joi.number() })
const schemaC = Joi.object({
  keyC1: Joi.string(),
  keyC2: schemaB  
})

Joi.validate({ keyC1: 'joi', keyC2: { keyB1: 'rocks!', keyB2: 3 } }, schemaC)
Túbal Martín
  • 709
  • 6
  • 6
37

You could use object.keys API

var nestedSchema = joi.object().keys({
    b: joi.number()
});

var base = joi.object({
    a: joi.string(),
    nestedData: nestedSchema
});
Francesco Pezzella
  • 1,755
  • 2
  • 15
  • 18
  • 1
    Thank you ... but there is a typo. It should be joi.object().keys instead of joi.object.keys – Anshul Apr 20 '16 at 11:05
4

just a tip based on Francesco's accepted answer:

if you need "nestedData" to be required -> "nestedData: nestedSchema.required()" in "base" will not work, you need to set it directly on "nestedSchema" just like any other parameter

    var nestedSchema = joi.object().keys({
        b: joi.number()
    })
    .required();

    var base = joi.object({
        a: joi.string(),
        nestedData: nestedSchema
    });
fkvestak
  • 539
  • 7
  • 20
0

With Joi version 17.6.0 you can use the valid function as below

const schema = Joi.object({
   type: Joi.string().valid('android', 'ios').insensitive()
})

This will throw an error if the type property is not android or ios

M.Shaltoot
  • 33
  • 7
0
const base = joi.object({
     a: joi.string(),
     nestedData: joi.object({b: joi.number()})
});
  • Welcome to Stackoverflow. This question is asked more than 6 years ago and it has an accepted answer. Please add some details about the reason you are adding a new answer. – MD Zand Dec 01 '22 at 14:10