Search code examples
typescriptvalidationtestingjoi

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

  • The answer was quite simpel and straightforward:

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

    Thanks Ankh!