How do I merge two Zod schemas?

Hey guys, I am creating a form with react-hook-form and Zod. The form was too long, so I decided to divide it into multi step form, with each step having separate Zod schema. I am storing the form data locally until all steps are complete. Now, I want a Zod schema for combining the schemas and perform a validation before I send the data to the server. I am unable to find the right solution. Can somebody please help me?
Solution:
``` const schema1 = z.object({ name: z.string(), }); ...
Jump to solution
4 Replies
Solution
Juraj98
Juraj98•7mo ago
const schema1 = z.object({
name: z.string(),
});

const schema2 = z.object({
age: z.number(),
});

const schema3 = schema1.and(schema2)
const schema1 = z.object({
name: z.string(),
});

const schema2 = z.object({
age: z.number(),
});

const schema3 = schema1.and(schema2)
Juraj98
Juraj98•7mo ago
Would this work for you?
muadpn
muadpn•7mo ago
import { z } from "zod";

const pathSchema = z.object({
nextPath: z.enum(["page", "layout"]),
webPath: z.string(),
});

// Define the schema for the "tag" type
const tagSchema = z.object({
tags: z.array(z.string()),
});

// Define the overall schema with a discriminator
export const revalidateRequestSchema = z
.object({
type: z.enum(["path", "tag"]),
})
.and(
z.union([
z.object({
type: z.literal("path"),
path: pathSchema,
}),
z.object({
type: z.literal("tag"),
tags: tagSchema.shape.tags,
}),
])
);

export type RevalidateRequestData = z.infer<typeof revalidateRequestSchema>;
import { z } from "zod";

const pathSchema = z.object({
nextPath: z.enum(["page", "layout"]),
webPath: z.string(),
});

// Define the schema for the "tag" type
const tagSchema = z.object({
tags: z.array(z.string()),
});

// Define the overall schema with a discriminator
export const revalidateRequestSchema = z
.object({
type: z.enum(["path", "tag"]),
})
.and(
z.union([
z.object({
type: z.literal("path"),
path: pathSchema,
}),
z.object({
type: z.literal("tag"),
tags: tagSchema.shape.tags,
}),
])
);

export type RevalidateRequestData = z.infer<typeof revalidateRequestSchema>;
maybe this helps? soo valid object are either:
* @example {"type" : "path", path: { nextPath: "page", webPath: "/projects"}}
* @example {"type" : "tag", tag: ["project_id", "data"]}
* @example {"type" : "path", path: { nextPath: "page", webPath: "/projects"}}
* @example {"type" : "tag", tag: ["project_id", "data"]}
CyberHero36
CyberHero36OP•7mo ago
Thanks, this helped. I was looking into the docs for union, intersection, etc. and did not check for and method 😓
Want results from more Discord servers?
Add your server