0PricingLogin
tRPC End-to-End Type Safe APIs · Lesson

Defining Complex Zod Schemas

Learn to create advanced Zod schemas for objects, arrays, and custom validation rules.

Beyond Basic Zod Types

Welcome back! In the previous lesson, we learned about Zod's basic types like string, number, and boolean. These are great for simple validations.

But real-world data is rarely simple! We often deal with complex structures like user profiles, product lists, or nested configurations.

Today, we'll dive into defining schemas for these more intricate data types, making your tRPC APIs even more robust.

Crafting Object Schemas

The z.object() method is your go-to for validating JavaScript objects. You define each property's schema within it.

  • Each key in the object corresponds to a property in your data.
  • The value for each key is another Zod schema, defining that property's type and rules.
  • By default, all properties defined in z.object() are required.

Let's see how to define a schema for a simple user object:

import { z } from 'zod';

const UserProfileSchema = z.object({
  username: z.string().min(3),
  email: z.string().email(),
  age: z.number().int().positive()
});

All lessons in this course

  1. Introduction to Zod Schemas
  2. Defining Complex Zod Schemas
  3. Integrating Zod in tRPC Procedures
  4. Transforming and Refining Zod Data
← Back to tRPC End-to-End Type Safe APIs