Course contentsShow
← React
Lesson 1244 of 2,39631. Forms in ReactFree lesson

Complex Schemas: Nested Objects and Arrays

Building schemas for complex form structures with nested objects, arrays, and conditional validation logic.

Complex Schemas: Nested Objects and Arrays

What you'll learn: How to use Zod to validate forms with nested objects, arrays of items, and conditional rules that mirror real-world data structures.

Beyond Flat Forms

Most real forms aren't just a list of independent fields. You might have a user with an address object, or a project with an array of team members, or conditional validation where one field's rules depend on another's value. Zod handles these complex structures elegantly.

Nested Objects

When your form data has structure, your schema should reflect it:

const userSchema = z.object({
  name: z.string().min(1),
  address: z.object({
    street: z.string(),
    city: z.string(),
    zipCode: z.string().regex(/^\d{5}$/),
  }),
});

Your form state mirrors this: user.address.city validates against the nested rule.

Arrays of Items

For repeating data like a list of phone numbers or tags:

const contactSchema = z.object({
  name: z.string(),
  emails: z.array(z.string().email()).min(1),
  tags: z.array(z.string()).optional(),
});

Use .min() and .max() on arrays to enforce quantity rules.

Conditional Validation

Make rules depend on other field values using refine:

const formSchema = z.object({
  needsShipping: z.boolean(),
  address: z.string().optional(),
}).refine(
  (data) => !data.needsShipping || data.address,
  { message: "Address required when shipping", path: ["address"] }
);

Think of it like: "If X is true, then Y must be valid."

Array of Objects

The most complex pattern combines both:

const teamSchema = z.object({
  members: z.array(
    z.object({
      name: z.string(),
      role: z.enum(["admin", "member"]),
    })
  ).min(1),
});

Key Takeaway: Zod schemas mirror your data structure exactly—nested objects become nested schemas, arrays become z.array(), and conditional logic becomes refine(), making complex form validation type-safe and readable.