Clean user input
Normalize form fields such as usernames or display names before validation and storage.
Zod · Module
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.
.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.
z.string().trim()A string with surrounding whitespace removed.
.trim() on z.string() to remove surrounding whitespace during parsing..trim() as a mutating transform, meaning the parsed output is changed..trim() is one of several built-in string transformations available alongside casing and Unicode normalization methods..trim() transforms the parsed value; it is not merely a validation check.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.
Normalize form fields such as usernames or display names before validation and storage.
Ensure whitespace-only input fails a following .min(1) constraint.
Prepare values for downstream comparisons where accidental surrounding spaces should not matter.
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).
.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().
.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