如何使用 Joi 验证自定义类型?
假设我们有这样的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
答案非常简单明了:
谢谢 Ankh!
The answer was quite simpel and straightforward:
Thanks Ankh!