vee-validate
vee-validate copied to clipboard
Support ZodDiscriminatedUnion
Is your feature request related to a problem? Please describe.
When creating dependent forms it would be nice to express the form dependencies via Zod.
Describe the solution you'd like
z.discriminatedUnion
allows us to do this in a nice matter.
const validationSchema = toTypedSchema(
z.object({
type: z
.enum(["my-optional-number", "my-string", "my-enum", "nothing"])
.default("my-enum"),
foo: z.discriminatedUnion("type", [
z.object({
type: z.literal("my-optional-number"),
data: z.number().default(42).optional(),
}),
z.object({
type: z.literal("my-string"),
data: z.string().default("some string"),
}),
z.object({
type: z.literal("my-enum"),
data: z.enum(["red", "green", "blue"]).default("red"),
}),
z.object({
type: z.literal("nothing"),
data: z.never(),
}),
]),
})
);
Based on the type
the schema validation in the schema above adjusts.
type === 'my-optional-number' => foo validates to number
type === 'my-string' => foo validates to string
type === 'my-enum' => foo validates to enum
type === 'nothing' => foo validates to never
Describe alternatives you've considered
https://www.shadcn-vue.com/docs/components/auto-form.html uses a second dsl (dependencies) to solve the issue in a different way. But this approach creates the need to describe the dependencies via second api.
This makes the schema itself useless for the other tasks.
Here is an example using react-hook-forms that implements such a logic.