String validation in Zod
String validators check length and content. String transforms like trim clean up user input before you use it.
How it works
- Chain validations. The
Usernameschema chains.min(3),.max(12)and.regex(). Each test value prints either the parsed string or the first issue message. [1] - 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] - 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);
Try inputs like "ab" or "has space" to see which rule reports an issue. Code written by AgentGid [1].
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
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.