I have a main Zod schema defined as follows:
const QuestionSchema = z.object({
Question: z.string(),
QuestionLevel: z.nativeEnum(QuestionLevel),
Metadata: z.object({
Curriculum: z.object({ Name: z.string(), Id: z.number() }),
Qualification: z.array(z.object({ Name: z.string(), Id: z.number() })),
Subjects: z.array(z.object({ Name: z.string(), Id: z.number() })).nonempty(),
Modules: z.array(z.object({ Name: z.string(), Id: z.number() })).nonempty(),
PastPaperReference: z
.object({
Papers: z.array(z.string()).optional(),
Months: z.array(z.string()).optional(),
Years: z.array(z.string()).optional(),
})
.optional()
.nullable(),
}),
});
I then extend this schema to create another schema called SubPartQuestionZodSchema
:
const SubPartQuestionZodSchema = QuestionSchema.extend({
Type: z.literal(QuestionTypes.SUB_PART),
Questions: z.array(z.lazy(() => QuestionZodSchema)),
Metadata: z.object({
...QuestionSchema.shape.Metadata.shape,
Modules: z.null().or(z.undefined()),
Topics: z.null().or(z.undefined()),
Difficulty: z.null().or(z.undefined()),
DepthOfKnowledge: z.null().or(z.undefined()),
}),
});
Finally, I use SubPartQuestionZodSchema
in a discriminated union like this:
export const QuestionZodSchema = z.discriminatedUnion("Type", [
MultiChoiceQuestionZodSchema,
FillInTheBlankQuestionZodSchema,
EssayQuestionZodSchema,
SinglelineZodSchema,
MultilineZodSchema,
SubPartQuestionZodSchema,
]);
I need to add a conditional validation to SubPartQuestionZodSchema
such that if QuestionLevel === "SUBJECT"
, then it’s okay for the Modules array to be empty or null. However, if QuestionLevel is any other value, the Modules array should be non-empty and validated according to the original schema.
How can I achieve this conditional validation for the Modules array in the SubPartQuestionZodSchema
?