Capítulo 4 de 61

Chapter 4: Strings — Validation & Transforms

Core Idea

z.string() carries a set of chainable validation methods (length, pattern, prefix/suffix) and transform methods (trim, case conversion) that cover the majority of everyday string handling without a custom refinement.

Key Concepts

  • .min() / .max() / .length(): bound the string length; .nonempty() is an alias for .min(1).
  • .regex() / .startsWith() / .endsWith() / .includes(): pattern and substring checks.
  • .uppercase() / .lowercase(): assert the string is already all-upper/lower case (a check, not a transform).
  • .trim() / .toLowerCase() / .toUpperCase() / .normalize(): transform methods that rewrite the value during parsing.
  • Zod Mini equivalent: every check has a .check(z.xxx()) form, e.g. z.string().check(z.minLength(5)) instead of z.string().min(5).
  • Unicode-aware length: .length()/.min()/.max() count Unicode code points, not UTF-16 code units — a single emoji outside the Basic Multilingual Plane counts as one, but combining marks and ZWJ sequences count as several.

Code Examples

z.string().max(5);
z.string().min(5);
z.string().length(5);
z.string().nonempty(); // alias for .min(1)
z.string().regex(/^[a-z]+$/);
z.string().startsWith("aaa");
z.string().endsWith("zzz");
z.string().includes("---");

z.string().trim();        // trim whitespace
z.string().toLowerCase();
z.string().normalize();   // normalize unicode characters
  • What it demonstrates: the standard set of string checks and transforms, all chainable off z.string().

Anti-patterns

  • Assuming .length() counts UTF-16 units: z.string().length(1).parse("😀") passes because the emoji is one code point even though it's two UTF-16 units — don't rely on .length matching str.length in JS for non-BMP characters.

Key Takeaways

  1. Reach for the built-in string checks before writing a custom .refine() — they cover length, pattern, and case out of the box.
  2. Transform methods (.trim(), .toLowerCase()) mutate the parsed output, not just validate — the returned value differs from the input.
  3. String length checks count Unicode code points; test carefully around emoji and combining characters.

Connects To

  • String formats: for validating string content type (email, URL, UUID) rather than shape.
  • Transforms: for string manipulation beyond the built-in trim/case methods.