如何使用 Joi 验证自定义类型?

发布于 2025-01-11 17:50:53 字数 706 浏览 0 评论 0原文

假设我们有这样的 TypeScript 代码:

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

如何配置 Joi,以便在验证 fido 时也验证 fido 最喜欢的食物?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

黑色毁心梦 2025-01-18 17:50:53

答案非常简单明了:

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

谢谢 Ankh!

The answer was quite simpel and straightforward:

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

Thanks Ankh!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文