[英]Joi: filter values based on other key's value
我有一个如下所示的类型列表
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', 'BANANA', ....],
其他类别也是如此。
我尝试使用 refs 但没有奏效。 有人可以帮我解决这个问题吗?
如果您不介意使用非 Joi 解决方案,您可以通过键动态访问对象值。
const categories = {
BAKERY: ['ADDON', 'AMERICAN', 'ANDHRA', ....],
FRUITS: ['APPLE', 'BANANA', ....],
RESTAURANT: ['VEG', 'NONVEG', ....],
};
const type = "FRUITS";
console.log(categories[type]); // ['APPLE', 'BANANA', ....],
所以你可以这样做:
// Example data to validate
const data = {
type: "FRUITS",
category: "APPLE"
};
// enums example:
const enums = {
categories: {
RESTAURANT: ['ADDON', 'AMERICAN', 'ANDHRA', ....],
FRUITS: ['APPLE', 'BANANA', ....],
RESTAURANT: ['VEG', 'NONVEG', ....],
},
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', 'BANANA', ....])
.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()
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.