'How to validate custom types with Joi?

Lets say we have this TypeScript code:

export class Dog {
  name = 'Fido'
  favoriteFood: Food | null = null
}

export class Food {
  name: string | null = null
}

export const DogSchema = Joi.object({
  name: Joi.string(),
  favoriteFood: Joi.object() // How to configure this correctly?? I would prefer to use FoodSchema in this line somehow
})

export const FoodSchema = Joi.object({
  name: Joi.string(),
})

const fido = new Dog()
fido.favoriteFood = new Food()
const res1 = DogSchema.validate(fido) // Gives no error!! 
const res2 = FoodSchema.validate(fido.favoriteFood) // Gives expected error: "name" must be a string

How can I configure Joi so when I validate fido the validation also validates fido's favorite food?



Solution 1:[1]

The answer was quite simpel and straightforward:

export const DogSchema = Joi.object({
  name: Joi.string(),
  favoriteFood: FoodSchema // Just put the schema here! 
})

Thanks Ankh!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mikael