Fields depending on other fields #954
-
Bit of a complex one and might be a job for a layer on top of Zod but I couldn't find a similar issue so figured I'd open one. I have a data structure that has a couple of fields that are required only if another field is set to some value. z.object({
entity: z.enum(["individual", "business"]),
firstName: z.string(),
lastName: z.string(),
companyName: z.string(),
companyNumber: z.string(),
}); If What's the best way to go about this? I was thinking refine but there's no access to the object within this function, another method I could think of was something akin to a tagged type union: type GeneralFields = { firstName: string; lastName: string }
type IndividualFields = { entity: "individual" } & GeneralFields
type BusinessFields = { entity: "business" } & {
companyName: string;
companyNumber: string;
}
type Fields = IndividualFields | BusinessFields; Is this possible to express with Zod? Thanks for such a great library! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
You can express the second example in zod as follows: const CompanyFields = z.object({ companyName: z.string(), companyNumber: z.string() })
const GeneralFields = z.object({ firstName: z.string(), lastName: z.string() })
const IndividualFields = z.object({ entity: z.literal("individual") }).and(GeneralFields)
const BusinessFields = z.object({ entity: z.literal("business") }).and(CompanyFields)
const Fields = IndividualFields.or(BusinessFields) |
Beta Was this translation helpful? Give feedback.
-
How can I access the errors for this schema? It used to work but now I can only access the literal property. zod: 3.11.6 |
Beta Was this translation helpful? Give feedback.
You can express the second example in zod as follows: