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(),
})
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
Jump to solution
2 Replies
Solution
mezo
mezo3mo ago
what happens if you define a new schema with the fields you want to edit and then use merge? https://zod.dev/?id=merge
Mugetsu
MugetsuOP3mo ago
Well it seems to be working. Extend here seems better choice after playing with it as it need less z props through out. Thank you for suggestion ! ❤️
Want results from more Discord servers?
Add your server