Home > OS >  validate an array of Enum in yup
validate an array of Enum in yup

Time:10-28

I need to validate an array of enums in yup.

I am using typescript so I have to utilize the exact type of the enums during validation. While using an array of strings seems to work, I want to validate the exact array of enums instead of strings. Is there a way to accomplish this?

I've added a working codesandbox as well https://codesandbox.io/s/clever-edison-3vqp1

Here's a snippet of what I intend to do

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();

CodePudding user response:

My suggestion is to validate your enum item by item:

import { object, string } from "yup";

enum DayEnum {
  Sunday = "Sunday",
  Monday = "Monday",
  Tuesday = "Tuesday",
  Wednesday = "Wednesday",
  Thursday = "Thursday",
  Friday = "Friday",
  Saturday = "Saturday"
}

const daysSchema = object({
  Sunday: string(),
  Monday: string(),
  Tuesday: string(),
  Wednesday: string(),
  Thursday: string(),
  Friday: string(),
  Saturday: string()
});

You can also check the codesandbox version.

CodePudding user response:

I was able to solve this thanks to this comment: https://github.com/jquense/yup/issues/1497#issue-1034140602

The solution looks like this

const daysSchema = object({
  days_of_week: array(
        mixed<DayEnum>().oneOf(Object.values(DayEnum)).required()
    ).ensure()
});
  • Related