在 yup 中验证枚举数组
validate an array of Enum in yup
我需要验证是的枚举数组。
我使用的是打字稿,所以我必须在验证期间使用枚举的确切类型。虽然使用字符串数组似乎可行,但我想验证确切的枚举数组而不是字符串。有办法实现吗?
我也添加了一个可用的codesandbox
https://codesandbox.io/s/clever-edison-3vqp1
这是我打算做的事情的片段
import { object, array } from "yup";
enum DayEnum {
Sunday = "Sunday",
Monday = "Monday",
Tuesday = "Tuesday",
Wednesday = "Wednesday",
Thursday = "Thursday",
Friday = "Friday",
Saturday = "Saturday"
}
const daysSchema = object({
// days_of_week: array(string()),
days_of_week: array(DayEnum)
});
const main = async () => {
console.log(
await daysSchema.isValid({
days_of_week: [DayEnum.Sunday, DayEnum.Saturday]
})
);
};
main();
多亏了这条评论,我才得以解决这个问题:https://github.com/jquense/yup/issues/1497#issue-1034140602
解决方案如下所示
const daysSchema = object({
days_of_week: array(
mixed<DayEnum>().oneOf(Object.values(DayEnum)).required()
).ensure()
});
我需要验证是的枚举数组。
我使用的是打字稿,所以我必须在验证期间使用枚举的确切类型。虽然使用字符串数组似乎可行,但我想验证确切的枚举数组而不是字符串。有办法实现吗?
我也添加了一个可用的codesandbox https://codesandbox.io/s/clever-edison-3vqp1
这是我打算做的事情的片段
import { object, array } from "yup";
enum DayEnum {
Sunday = "Sunday",
Monday = "Monday",
Tuesday = "Tuesday",
Wednesday = "Wednesday",
Thursday = "Thursday",
Friday = "Friday",
Saturday = "Saturday"
}
const daysSchema = object({
// days_of_week: array(string()),
days_of_week: array(DayEnum)
});
const main = async () => {
console.log(
await daysSchema.isValid({
days_of_week: [DayEnum.Sunday, DayEnum.Saturday]
})
);
};
main();
多亏了这条评论,我才得以解决这个问题:https://github.com/jquense/yup/issues/1497#issue-1034140602
解决方案如下所示
const daysSchema = object({
days_of_week: array(
mixed<DayEnum>().oneOf(Object.values(DayEnum)).required()
).ensure()
});