Bound string length
Usernames, labels, and other text fields must stay below a storage or UI limit.
Zod · Module
.max() adds an inclusive upper bound to a Zod schema. Its meaning depends on the schema: string length, array item count, file size, or a comparable maximum for dates and bigints.
.max() adds an upper-bound check to a schema. For strings it limits length, while the same method on arrays and files limits item count or file size; the page also documents date and bigint variants.
schema.max(value, params?)| Name | Type | Description |
|---|---|---|
value | number | bigint | Date | Maximum permitted value, length, count, date, bigint, or file size, depending on the schema type. |
params | error configuration | Optional error customization configuration. |
The same Zod schema instance with an added maximum constraint, enabling method chaining.
.max(n) after z.string() to impose an upper bound of n on string length..max(n) allows at most n elements while still validating each element against the element schema..max(date) to reject dates later than the supplied maximum, and the example demonstrates an error option..max() does not necessarily limit visible characters as users count them.import { z } from "zod";
const username = z.string().max(12);
console.log(username.safeParse("Ada").success); // true
console.log(username.safeParse("This name is too long").success); // falseCreates a string schema that accepts values whose length does not exceed 12.
Usernames, labels, and other text fields must stay below a storage or UI limit.
A request should accept only a limited number of records.
Uploads must stay within an application or infrastructure limit.
A timestamp or bigint must not exceed a defined boundary.
.max() method do?.max(value) adds an inclusive upper bound to the schema's relevant measurement. On strings it constrains length; on arrays it constrains the number of elements, and on files it constrains byte size.
Follow-up: How would you enforce an exact string length? Use .length(n), which requires the string to have exactly n characters under the documented string-length semantics.
For a string schema, z.string().max(5) accepts strings whose length is at most five and rejects longer values. The method is chainable, so additional string checks can follow it.
Follow-up: How can the validation error be customized? Pass the supported error configuration as the second argument, for example z.string().max(5, { error: "Too long" }).
.max()?The method is not limited to strings. The documentation shows .max() for arrays, dates, bigints, and files, with the constrained quantity depending on the schema type.
Follow-up: What is the array equivalent of a maximum string length? Use z.array(elementSchema).max(n) to allow no more than n items.
z.string().min()z.string().length()z.array().max()z.date().max()z.bigint().lte()fileSchema.max()