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

Transforming and Preprocessing Data

Using .transform() and .preprocess() to clean, coerce, or normalize form data before validation.

Transforming and Preprocessing Data

What you'll learn: How to clean and normalize user input before Zod validates it, ensuring your validation rules see consistent, properly-formatted data.

Sometimes users enter valid data in the "wrong" format—extra whitespace, mixed casing, or string numbers when you need actual numbers. Rather than writing complex validation rules to handle every variation, Zod lets you transform data first, then validate the cleaned result.

The .transform() Method

.transform() reshapes validated data after it passes your rules. It's like a post-processing step:

const schema = z.object({
  email: z.string().email().transform(val => val.toLowerCase()),
  age: z.string().transform(val => parseInt(val, 10))
});

The email becomes lowercase after passing email validation. The string age becomes a number after string validation passes.

The .preprocess() Method

.preprocess() cleans data before validation runs. It's like a pre-wash cycle:

const schema = z.object({
  username: z.preprocess(
    val => typeof val === 'string' ? val.trim() : val,
    z.string().min(3)
  )
});

Now " bob " becomes "bob" before the min-length check runs, so users won't fail validation due to accidental spaces.

Common Use Cases

  • Trimming whitespace: .preprocess() removes leading/trailing spaces
  • Normalizing case: .transform() standardizes to lowercase/uppercase
  • Type coercion: Converting string numbers to actual numbers
  • Sanitizing input: Removing special characters or formatting

Key Takeaway: Use .preprocess() to clean messy input before validation rules run, and .transform() to convert validated data into the exact shape your application needs. This keeps validation logic simple while handling real-world user behavior gracefully.