Utilizing a zod schema to validate an object containing an enum field:
enum Colour {
red: 'Red',
blue: 'Blue',
}
const schema = z.object({
colour: z.nativeEnum(Colour),
});
Received data from an API includes color values as either 'red' or 'blue', and the goal is to validate this using the provided schema. However, the nativeEnum function in the schema validates based on capitalized enum cases rather than the enum properties themselves:
enum Colour {
red: 'Red',
blue: 'Blue',
}
const schema = z.object({
colour: z.nativeEnum(Colour),
});
const rawInput1 = {
colour: 'red' // should be considered valid
};
const parsedInput1 = schema.parse(rawInput1); // this validation fails
const rawInput2 = {
colour: 'Red' // should be considered invalid
};
const parsedInput2 = schema.parse(rawInput2); // this validation passes
Is there a way to make zod validate based on the property in the enum instead of just the value? And why does this occur?
The reason for wanting to parse the enum properties and defining the enum that way is to utilize the colour
variable to extract its string value within the enum: Colour[parsedInput1.colour]
. This wouldn't be achievable if colour
remains the string value.