Skip to content
Agents tracked: 440 Downloads (7d): 202M down 19.5% GitHub stars: 10.4M Releases (7d): 607 Agent status: 3 with issuesSince last limit reset: Claude 28d · Codex 0d Updated Oct 21, 2026

String validation in Zod

String validators check length and content. String transforms like trim clean up user input before you use it.

All Zod examples Zod: usage and stats

String validation in Zod: screenshot of the example below running
The code below, running in Chromium on our server (Oct 12, 2026). Press Run to see it live and change it.

How it works

  1. Chain validations. The Username schema chains .min(3), .max(12) and .regex(). Each test value prints either the parsed string or the first issue message. [1]
  2. Clean input with transforms. .trim() and .toLowerCase() are added to the same schema. The input " Billie_99 " shows the cleaned value that is printed. [1]
  3. Check prefixes and code points. z.string().startsWith("sku-") checks a prefix. The last check uses .length(1) on an emoji, since length counts Unicode code points. [1]

Run and edit it

It runs in your browser, in a sandboxed frame that cannot see this site; the packages load from esm.sh only after you press Run.

import * as z from "zod";

const Username = z
  .string()
  .trim()
  .toLowerCase()
  .min(3)
  .max(12)
  .regex(/^[a-z0-9_]+$/);

const tests = ["  Billie_99 ", "ab", "has space", "averyveryverylongname"];

for (const t of tests) {
  const result = Username.safeParse(t);
  if (result.success) {
    console.log(`${JSON.stringify(t)} -> ${JSON.stringify(result.data)}`);
  } else {
    console.log(`${JSON.stringify(t)} -> error: ${result.error.issues[0].message}`);
  }
}

const Sku = z.string().startsWith("sku-");
console.log("sku-123 valid:", Sku.safeParse("sku-123").success);
console.log("abc-123 valid:", Sku.safeParse("abc-123").success);

// one emoji = one code point
console.log("emoji length(1):", z.string().length(1).safeParse("😀").success);
Ctrl/⌘ + Enter runs

Free for signed-in members, with a daily limit. Describe the change in plain words; the new code runs only in your browser.

Try inputs like "ab" or "has space" to see which rule reports an issue. Code written by AgentGid [1].

Checked Oct 12, 2026: it starts without errors in Chromium with zod 4.6.6. Needs WebGL.

More Zod examples

Handling errors with ZodError in Zod String formats in Zod: email, UUID, phone, datetime Type coercion in Zod Literal values in Zod

Sources

  1. Docs: Defining schemas

Explanations written by AgentGid from the official docs; the numbers in brackets point here. The code marked "written by AgentGid" is ours and free to copy.

Building something with Zod? Ask AgentGid →