MainAdvanced Examples
TLDR /Validation

Zod Cheatsheet

Help others learn from this page

Zod is a TypeScript-first schema declaration and validation library. With Zod, you define validation schemas using TypeScript types, and get automatic static type inference as well as runtime validation. It’s perfect for validating input data while ensuring strong typing across your TypeScript application.

Basic Validation

Define basic schemas for primitive types.

const stringSchema = z.string(); // Validates strings
const numberSchema = z.number(); // Validates numbers

Required Fields

By default, fields are required.

const userSchema = z.object({
  name: z.string(),
  age: z.number(),
});

Optional Fields

Use .optional() to define optional fields.

const userSchema = z.object({
  name: z.string(),
  age: z.number().optional(),
});

Default Values

Use .default() to set default values.

const userSchema = z.object({
  name: z.string(),
  age: z.number().default(18),
});

Nested Objects

Schemas can contain other schemas.

const addressSchema = z.object({
  street: z.string(),
  city: z.string(),
  postalCode: z.string(),
});

const userSchema = z.object({
  name: z.string(),
  address: addressSchema,
});

Arrays

Define arrays using .array().

const stringArraySchema = z.array(z.string());
const numberArraySchema = z.array(z.number());

Enums

Use .enum() to create enums for specific values.

const genderSchema = z.enum(['male', 'female', 'other']);

Union Types

Combine multiple types with .union().

const ageSchema = z.union([z.string(), z.number()]);

Refinements

Add custom validation logic with .refine().

const positiveNumberSchema = z.number().refine(val => val > 0, {
  message: 'Must be a positive number',
});

Async Validation

Use .refine() with async functions for asynchronous validation.

const emailSchema = z.string().refine(async val => await isEmailValid(val), {
  message: 'Invalid email',
});

Parsing and Error Handling

Use .safeParse() for safer validation with error handling.

const result = userSchema.safeParse(data);
if (!result.success) {
  console.error(result.error.format());
}

Type Inference

Zod automatically infers types.

type User = z.infer<typeof userSchema>;
// User type is automatically inferred

Schema Validation with parse()

Use .parse() to validate and throw an error on failure.

const validatedData = userSchema.parse(data);
// Throws error if validation fails

Schema Composition

Schemas can be composed with .merge() and .and(). This is useful for combining schemas.

const userWithAddressSchema = userSchema.merge(addressSchema);

Zod Error Handling

Zod’s error format includes path, message, and issues for detailed error reports.

const result = userSchema.safeParse(data);
if (!result.success) {
  console.error(result.error.issues);
}

Frequently Asked Questions

FAQ

What is Zod?
Zod is a TypeScript-first schema declaration and validation library that provides runtime validation and static type inference with zero dependencies.
Can I use Zod with JavaScript?
Zod is designed for TypeScript, but it also works with plain JavaScript. However, you'll miss out on the TypeScript-specific type inference features.
Can Zod be used for form validation?
Yes. Zod can be used to validate form inputs, ensuring that the form data meets the required criteria before submission.
What happens if a schema validation fails?
Zod will throw an error if you use `.parse()` or return a failed result with `.safeParse()`. The error will contain detailed information, including the validation issues.
Can Zod handle nested objects and arrays?
Yes. Zod supports deeply nested objects and arrays. You can combine schemas and use `.array()` and `.object()` to create complex validations.

Related Concepts

  • TypeScript Types: How Zod integrates seamlessly with TypeScript's type system.
  • Validation Libraries: A comparison of Zod with other validation libraries like Joi and Yup.
  • Schema Validation: Why schema validation is critical in ensuring secure and accurate data processing.

Found this helpful? Share it!