Theo's Typesafe CultTTC
Theo's Typesafe Cult2y ago
4 replies
Mugetsu

New Zod schema based on an existing one, with some fields having different validation rules?

Having some schema how I could re-use the schema and access some of its fields and change their validation to make up new schema.

const schema = z.object({
    details: z.object({
        name: z.string(),
        street: z.string(),
        coordinates: z.object({
            lat: z.string(),
            long: z.string(),
        }),
    }).partial().optional(),
    id: z.string().uuid(),
})

Given this schema I would like the
name
field to be required/min length and have a new schema from this initial one with the rest fields being as is. In the inital schema only
id
would be required with the sub-schema
id
and
name
should be required rest optional
Solution
what happens if you define a new schema with the fields you want to edit and then use merge? https://zod.dev/?id=merge
Was this page helpful?