Tutorial

Nested Zod Schema Validation

Compose nested Zod schemas for deeply structured forms, discriminate unions, and surface field-level errors with type-safe parse results.

On this page

  1. Introduction
  2. Model the nested shape
  3. Discriminate variants
  4. Parse safely
  5. Map paths to fields
  6. Refine with context
  7. Test the boundary
  8. Sources

Introduction

This guide covers nested Zod schema validation for deeply structured forms, a recurring concern in the form-validation scenario. Forms rarely stay flat: an order has a billing address, a shipping address, and a list of items, each with its own rules. Zod lets you compose schemas the way you compose types, so the validator mirrors the shape of the data and the parsed result is statically typed.

Model the nested shape

Define each sub-object as its own schema so an address is reusable across billing and shipping, and the top schema just references it.

The trade-off worth naming is that define each sub-object as its own schema so an address is reusable across billing and shipping, and the top schema just references it adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.

import { z } from 'zod';
const Address = z.object({
  street: z.string().min(1),
  city: z.string().min(1),
  zip: z.string().regex(/^\d{5}$/),
});
const Item = z.object({
  sku: z.string().min(1),
  qty: z.number().int().positive(),
  price: z.number().nonnegative(),
});
const Order = z.object({
  billing: Address,
  shipping: Address,
  items: z.array(Item).min(1),
});

Discriminate variants

Use z.discriminatedUnion when a payload has a tag field, so the validator picks the right branch and narrows the type in one step.

The trade-off worth naming is that use z.discriminatedunion when a payload has a tag field, so the validator picks the right branch and narrows the type in one step adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.

const Event = z.discriminatedUnion('kind', [
  z.object({ kind: z.literal('created'), id: z.string() }),
  z.object({ kind: z.literal('updated'), id: z.string(), patch: z.record(z.unknown()) }),
]);
const r = Event.safeParse(payload);
if (r.success) {
  if (r.data.kind === 'updated') r.data.patch; // narrowed
}

Parse safely

Prefer safeParse over parse so a bad payload returns a typed error instead of throwing, which keeps validation out of your error boundary.

The trade-off worth naming is that prefer safeparse over parse so a bad payload returns a typed error instead of throwing, which keeps validation out of your error boundary adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.

const r = Order.safeParse(input);
if (!r.success) {
  const fieldErrors = {};
  for (const issue of r.error.issues) {
    const key = issue.path.join('.');
    fieldErrors[key] = issue.message;
  }
  return { ok: false, fieldErrors };
}
return { ok: true, data: r.data };

Map paths to fields

Join the issue path with brackets for array indices so items[2].price maps to the third item price input without custom plumbing.

The trade-off worth naming is that join the issue path with brackets for array indices so items[2].price maps to the third item price input without custom plumbing adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.

Refine with context

Use superRefine when a rule needs the whole object, such as shipping required only when it differs from billing, and attach the issue to the right field.

The trade-off worth naming is that use superrefine when a rule needs the whole object, such as shipping required only when it differs from billing, and attach the issue to the right field adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.

const Order2 = Order.superRefine((v, ctx) => {
  if (v.shipping.street === v.billing.street && v.shipping.city !== v.billing.city) {
    ctx.addIssue({ code: 'custom', message: 'Same street must share city', path: ['shipping', 'city'] });
  }
});

Test the boundary

Assert a valid order passes, a missing items array fails with the right path, and a union mismatch names the expected branch, so the guarantee survives refactors.

The trade-off worth naming is that assert a valid order passes, a missing items array fails with the right path, and a union mismatch names the expected branch, so the guarantee survives refactors adds a measurable step to the hot path, so measure it before assuming it is free. A reasonable approach is to validate once at the edge, fail closed with a structured error, and log the rejection reason so a spike in bad input is visible on a dashboard rather than silent. Pair the implementation with a test that asserts a valid payload passes and at least one representative violation is rejected with the expected message; this is the cheapest way to keep the guarantee honest as the schema evolves.

Sources

Sources: Zod docs, Astro content collections.

FAQ

How do I surface errors for a nested field like items[2].price?
Zod issues carry a path array; join it with dots or brackets to build a field key that maps directly to your form state, so items.2.price or items[2].price reaches the right input.
Is discriminated union validation expensive?
It is a single key check plus the matched branch, so it is cheap and also gives a narrowed type for each variant, which removes a class of runtime casts.

Related Examples