I'm trying to validate a form with Zod and react-hook-form, and I need to make some fields required based on the value of other field. Here is my schema:
const formSchema = z.object({
cli_rut: z.string(),
cli_persona_natural: z.enum(["SI", "NO"]),
cli_nombres: z.string().optional(),
cli_apellido_paterno: z.string().optional(),
cli_apellido_materno: z.string().optional(),
cli_razon_social: z.string().optional(),
cli_estado: z.string().default("ACTIVO").optional(),
});
in this case I need to make required cli_nombres, cli_apellido_materno, and cli_apellido_paterno if cli_persona_natural = "SI", any ideas of how can i do it? Thanks
I'm expecting the fields to be required if cli_persona_natural is "SI"
You can use the
superRefinemethod to specify additional constraints like this, or you could usediscriminatedUnionin this case and end up with slightly stronger types.Super Refine Approach:
Discriminated Union Approach
This approach has a benefit with the types. If you check the value of
cli_persona_naturalyou will get type inference about whether or not the other fields are required.