问题描述
我有如下类型列表
const types = ['BAKERY','FRUITS','RESTAURANT',...];
此数组的长度未知。我为上述每种类型都有一个相应的类别列表,如下所述
const categories = {
RESTAURANT: ['ADDON','AMERICAN','ANDHRA',....],FRUITS: ['APPLE','BANANA',RESTAURANT: ['VEG','NONVEG',};
我想根据所选的类型来验证类别的模式。
const itemJoiSchema = Joi.object({
type: Joi.string()
.valid(...enums.types)
.required(),category: Joi.string()
.valid(............) // Here i want to accept only the values which fall into selected type above
.uppercase()
.required()
});
如果我选择type: 'FRUITS',
,则该类别应只接受['APPLE',
中的一个,其他类别也应类似。
我尝试使用裁判,但没有成功。有人可以帮我吗?
解决方法
如果您不介意使用非Joi解决方案,则可以通过键动态访问对象值。
const categories = {
BAKERY: ['ADDON','AMERICAN','ANDHRA',....],FRUITS: ['APPLE','BANANA',RESTAURANT: ['VEG','NONVEG',};
const type = "FRUITS";
console.log(categories[type]); // ['APPLE',
因此您可以这样做:
// Example data to validate
const data = {
type: "FRUITS",category: "APPLE"
};
// enums example:
const enums = {
categories: {
RESTAURANT: ['ADDON',},types: ['BAKERY','FRUITS','RESTAURANT',...]
}
const itemJoiSchema = Joi.object({
type: Joi.string()
.valid(...enums.types)
.required(),category: Joi.string()
.valid(...enums.categories[data.type] || [])
.uppercase()
.required()
});
由于data.type
的值为"FRUITS"
,它将通过categories.FRUITS
作为有效数组。结果将等于此
// Example data to validate
const data = {
type: "FRUITS",category: "APPLE"
};
const itemJoiSchema = Joi.object({
type: Joi.string()
.valid(...enums.types)
.required(),category: Joi.string()
.valid(...['APPLE',....])
.uppercase()
.required()
});
注意:|| []
用于防止用户传递错误的type
时出错。
工作示例:https://repl.it/repls/SuperAlienatedWorkplace。更改data.type
的值,您将看到有效的类别值相应地更改
您可以尝试使用Joi的.when()
方法
类似的东西
const itemJoiSchema = Joi.object({
type: Joi.string()
.valid(enums.types)
.required(),category: Joi.string()
.when(type { is: 'FRUIT',then: joi.valid(categories.FRUIT })
// etc
.uppercase()
.required()
});