Capítulo 5 de 61

Chapter 5: String Formats — Identifiers, URLs & Contact Info

Core Idea

Zod ships dozens of ready-made string-format validators (z.email(), z.uuid(), z.url(), z.e164(), ...) so common formats don't need hand-written regexes.

Key Concepts

  • z.email(): strict, Gmail-like email regex by default; pass { pattern: ... } to swap in z.regexes.html5Email, z.regexes.rfc5322Email, or z.regexes.unicodeEmail.
  • z.uuid({ version }): validates RFC 9562/4122 UUIDs; z.uuidv4()/z.uuidv6()/z.uuidv7() are version-specific shortcuts. z.guid() validates any UUID-like identifier without the RFC version-bit constraint.
  • z.url(): validates any WHATWG-compatible URL via the native URL constructor (permissive — accepts mailto: too); accepts hostname/protocol regex filters. z.httpUrl() is the pre-filtered "http/https only, real domain hostname" shortcut.
  • z.url({ normalize: true }): rewrites the parsed value to the URL-normalized form.
  • z.e164(): validates E.164 phone numbers (+, non-zero country code, 7-15 digits).
  • z.jwt({ alg }): validates JSON Web Token structure, optionally pinned to an algorithm.

Code Examples

z.email();
z.email({ pattern: z.regexes.html5Email }); // browser input[type=email] rules

z.uuid({ version: "v4" });
z.uuidv7();
z.guid(); // any UUID-like identifier, version bits not enforced

const url = z.httpUrl(); // http(s) only, real domain hostname
url.parse("https://example.com"); // ok
url.parse("mailto:noreply@zod.dev"); // throws (httpUrl, unlike url, rejects non-http schemes)

z.e164().parse("+15555555555"); // ok
z.e164().parse("555-555-5555"); // throws
  • What it demonstrates: format validators are pre-built but tunable via options rather than requiring a custom regex.

Reference Tables

FormatSchemaNotes
Emailz.email()swap regex via pattern
UUIDz.uuid(), z.uuidv4/6/7(), z.guid()version-checked vs. any UUID-like string
URLz.url(), z.httpUrl()z.url() is permissive (any WHATWG scheme); z.httpUrl() restricts to http/https + real domain
Phonez.e164()E.164 format only
JWTz.jwt({ alg })structural validation, optional algorithm pin

Anti-patterns

  • Using z.url() when you mean "a web page URL": z.url() accepts any WHATWG URL, including mailto: and other non-http schemes — use z.httpUrl() when the value must be a fetchable web address.

Key Takeaways

  1. Prefer the built-in format validators over hand-rolled regexes — they're tuned to match real-world edge cases (e.g. the email regex mirrors Gmail's rules).
  2. z.url() and z.httpUrl() are not interchangeable — z.url() is intentionally permissive.
  3. UUID validation has three tiers: version-pinned (z.uuidv4()), any-version-RFC-compliant (z.uuid()), and any-UUID-shaped string (z.guid()).

Connects To

  • String Formats — Dates, Network & Hashes: the remaining format validators (ISO dates, IP addresses, hashes, custom formats).
  • Custom: z.stringFormat() for defining your own named format when none of the built-ins fit.