Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Composing and Reusing Schemas | Advanced Validation with Zod
Zod Forms in React

bookComposing and Reusing Schemas

When building complex forms, you often need to validate data that shares structure with other parts of your application. Instead of rewriting validation logic for each form, you can compose and reuse Zod schemas using the .merge() and .extend() methods. These methods allow you to build modular, maintainable validation rules by combining or enhancing existing schemas.

The .merge() method combines two schemas into one, merging their shape and validation logic. This is useful when you want to create a new schema that includes fields from multiple sources. For instance, if you have a userSchema and an addressSchema, you can merge them to validate a user with an address.

The .extend() method lets you add new fields to an existing schema. This is helpful when you need a base schema for most cases but want to add extra fields for specific scenarios. By extending schemas, you avoid duplicating rules and keep your validation logic organized.

Reusing schemas is especially powerful for common data structures like addresses or user profiles. Instead of defining address validation in every form, you can define an addressSchema once and use it wherever an address is needed.

Suppose you have a form that collects both user information and address details. You can define each schema separately and reuse them across different forms. Here is how you might structure your schemas in markdown:

const addressSchema = z.object({
  street: z.string().min(1, "Street is required"),
  city: z.string().min(1, "City is required"),
  zip: z.string().regex(/^\d{5}$/, "Invalid ZIP code"),
});

const userSchema = z.object({
  name: z.string().min(1, "Name is required"),
  email: z.string().email("Invalid email address"),
});

// Merge schemas to create a full profile schema
const profileSchema = userSchema.merge(addressSchema);

// Or extend userSchema with address fields
const extendedUserSchema = userSchema.extend({
  street: z.string().min(1, "Street is required"),
  city: z.string().min(1, "City is required"),
  zip: z.string().regex(/^\d{5}$/, "Invalid ZIP code"),
});

By composing schemas in this way, you can reuse addressSchema and userSchema in multiple forms, ensuring consistency and reducing maintenance.

question mark

What is a key benefit of composing Zod schemas with .merge() or .extend()?

Select the correct answer

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 2

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

bookComposing and Reusing Schemas

Свайпніть щоб показати меню

When building complex forms, you often need to validate data that shares structure with other parts of your application. Instead of rewriting validation logic for each form, you can compose and reuse Zod schemas using the .merge() and .extend() methods. These methods allow you to build modular, maintainable validation rules by combining or enhancing existing schemas.

The .merge() method combines two schemas into one, merging their shape and validation logic. This is useful when you want to create a new schema that includes fields from multiple sources. For instance, if you have a userSchema and an addressSchema, you can merge them to validate a user with an address.

The .extend() method lets you add new fields to an existing schema. This is helpful when you need a base schema for most cases but want to add extra fields for specific scenarios. By extending schemas, you avoid duplicating rules and keep your validation logic organized.

Reusing schemas is especially powerful for common data structures like addresses or user profiles. Instead of defining address validation in every form, you can define an addressSchema once and use it wherever an address is needed.

Suppose you have a form that collects both user information and address details. You can define each schema separately and reuse them across different forms. Here is how you might structure your schemas in markdown:

const addressSchema = z.object({
  street: z.string().min(1, "Street is required"),
  city: z.string().min(1, "City is required"),
  zip: z.string().regex(/^\d{5}$/, "Invalid ZIP code"),
});

const userSchema = z.object({
  name: z.string().min(1, "Name is required"),
  email: z.string().email("Invalid email address"),
});

// Merge schemas to create a full profile schema
const profileSchema = userSchema.merge(addressSchema);

// Or extend userSchema with address fields
const extendedUserSchema = userSchema.extend({
  street: z.string().min(1, "Street is required"),
  city: z.string().min(1, "City is required"),
  zip: z.string().regex(/^\d{5}$/, "Invalid ZIP code"),
});

By composing schemas in this way, you can reuse addressSchema and userSchema in multiple forms, ensuring consistency and reducing maintenance.

question mark

What is a key benefit of composing Zod schemas with .merge() or .extend()?

Select the correct answer

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 2
some-alt