Zod conditional required/optional validation

I am using React Hook Form and Zod. I want make some fields optional/required based on other inputs.

Here's an example:
const schema = z.object({
  type: z.enum(['image', 'video', 'image-and-video', 'other']),
  image: z.custom<File>(),
  video: z.custom<File>(),
  otherNonMatchingKey: z.custom<File>(),
})

I want image to be required only when type: image is selected and vice-versa.
Solution
if you have a more then two options this solution will be nicer

const enumToField = {
  video: "videoFile",
  audio: "audioFile",
  ...
};

schema
  .refine((d) => d[enumToField[d.type]] !== undefined);
Was this page helpful?