I am currently attempting to utilize Zod schema validation for data with varying constraints depending on the value of an enumeration field (generated by Prisma). The data can take the following formats:
{ discriminatorField: "VAL1", otherField: "any string" }
{ discriminatorField: "any other allowed string besides VAL1", otherField: undefined }
It appears that this can be achieved using z.discriminatedUnion()
as shown below:
const schema = z.discriminatedUnion("discriminatorField", [
z.object({ discriminatorField: z.literal("VAL1"), otherField: z.string()}),
z.object({ discriminatorField: z.literal("VAL2"), otherField: z.string().optional()}),
// ... must list all possible enum values as literal conditions here?
])
While this method works, it requires listing out all potential enum values for discrimination. I attempted using z.nativeEnum(MyEnum)
instead of z.literal("VAL2")
in the code above, but Zod raised an error about overlapping values. Although technically correct, I had hoped it would prioritize the first matching case.