Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Zod · Module

.trim

z.string().trim() creates a string schema that removes surrounding whitespace from parsed values. It is a built-in string transformation that can be chained with other string checks and transforms.

How it works

.trim() is a string transformation in Zod. It removes surrounding whitespace from an input string and returns the trimmed value, so subsequent string checks operate on the transformed result.

Syntax

z.string().trim()

Returns

A string with surrounding whitespace removed.

Key points

  • Call .trim() on z.string() to remove surrounding whitespace during parsing.
  • Zod documents .trim() as a mutating transform, meaning the parsed output is changed.
  • When used through a codec, decoding a padded string returns the trimmed string.
  • The documented codec example also shows encoding a padded string produces the trimmed value.
  • .trim() is one of several built-in string transformations available alongside casing and Unicode normalization methods.

Common mistakes

  • .trim() transforms the parsed value; it is not merely a validation check.

Example: Trim a username

import { z } from "zod";

const username = z.string().trim().min(1);

console.log(username.parse("  ada  ")); // "ada"

The schema removes surrounding whitespace before applying the non-empty constraint.

When to use it

Clean user input

Normalize form fields such as usernames or display names before validation and storage.

Reject blank values

Ensure whitespace-only input fails a following .min(1) constraint.

Canonicalize text

Prepare values for downstream comparisons where accidental surrounding spaces should not matter.

Interview questions

QWhat does z.string().trim() do?

It is declared as z.string().trim(). Parsing a string such as " hello " produces "hello", because the transform removes surrounding whitespace.

Follow-up: How would you make the trimmed result non-empty? Chain a constraint after the transform, for example z.string().trim().min(1).

QWhat type of input does .trim() handle?

It belongs on a string schema, so the input must first satisfy z.string(). After parsing, the output is the whitespace-trimmed string.

Follow-up: How can preprocessing accept nullable input? Use z.preprocess to call .trim() conditionally, then validate the resulting value with z.string().

QWhere does .trim() fit in a Zod string pipeline?

.trim() can be combined with other string methods in a schema chain. For example, trimming before .min(1) ensures the length check sees the normalized value.

Follow-up: What is the difference between trimming and lowercasing? Trimming removes surrounding whitespace, while toLowerCase() changes letter casing.

  • z.string()
  • z.string().toLowerCase()
  • z.string().toUpperCase()
  • z.string().normalize()
  • z.preprocess

Source: Defining schemas | Zod. Checked 2026-10-15.