Fixed-length strings
Require a fixed-size identifier, such as a five-code-point username or short token.
Zod · Module
.length(n) requires a string or array to have exactly n units according to Zod’s counting rules. Strings are measured in Unicode code points; arrays are measured by item count.
.length(n) adds an exact-length constraint to a string or array schema. For strings, Zod counts Unicode code points rather than UTF-16 code units; for arrays, it requires exactly the specified number of items.
z.string().length(n)
z.array(elementSchema).length(n)| Name | Type | Description |
|---|---|---|
length | number | The exact length or item count required by the schema. |
A schema that validates strings or arrays with exactly the specified length; parsing returns the original validated value.
.length(n) after z.string() to require an exact string length.import { z } from "zod";
const username = z.string().length(5);
console.log(username.parse("alice")); // "alice"
// username.parse("al"); // throws a ZodErrorCreates a string schema that accepts exactly five Unicode code points.
Require a fixed-size identifier, such as a five-code-point username or short token.
Ensure a tuple-like collection has an exact number of elements while retaining array-item validation.
Validate Unicode-sensitive input where code-point counting is preferable to UTF-16 unit counting.
z.string().length(5) enforce?Use z.string().length(n) when a string must contain exactly n Unicode code points. Parsing succeeds only when the constraint is met.
Follow-up: How would you validate an exact number of array elements? Use z.array(elementSchema).length(n), which checks the array item count.
It rejects strings whose Unicode code-point count is not exactly the supplied number. This differs from counting UTF-16 code units in JavaScript.
Follow-up: Why can an emoji expose this difference? An emoji outside the Basic Multilingual Plane can count as one code point but occupy two UTF-16 units.
.length() apply only to strings?The method is also available on arrays, where .length(5) means the array must contain exactly five items. The element schema still validates each item.
Follow-up: How can a transformed string expose its JavaScript length? Pipe into z.transform(val => val.length), while remembering that this uses JavaScript's length behavior.
z.string().min()z.string().max()z.array()z.transform()