Zod Length Constraints: Minimum and Maximum


In Zod, length constraints are used to control how short, long, or exact a value can be using the .min(), .max(), and .length() methods.

Length constraints in Zod solve real problems like preventing users from submitting too-short passwords, overly long text inputs, invalid array sizes, or data that doesn’t meet business rules — ensuring your app receives consistent, valid, and secure data before processing it.

Try It Yourself: Quick Example

// Define schema with length constraints
const userSchema = z.object({
  username: z.string().min(3).max(15),   // must be 3–15 chars
  password: z.string().min(8),           // at least 8 chars
  pin: z.string().length(4),             // exactly 4 chars
});

// Test it out
const result = userSchema.safeParse({
  username: "sharuk",
  password: "12345678",
  pin: "1234",
});

In this example, the schema defines three fields — username, password, and pin — each with specific length rules.

The username must be between 3 and 15 characters, ensuring it’s neither too short nor too long. The password must have a minimum of 8 characters, enforcing stronger security. The pin must contain exactly 4 characters, making it ideal for fixed-length numeric or code inputs.

When the data is passed to safeParse(), Zod checks each field against these rules and returns either validated data or a detailed error object.

Error Handling with Zod Length Constraints

if (!result.success) {
  console.log("Validation failed!");
  console.log(result.error.errors);
} else {
  console.log("Validation passed!");
  console.log(result.data);
}

When you use .safeParse(), Zod returns an object with a success flag.

  • If success is true, result.data contains the validated data.
  • If success is false, result.error.errors provides a detailed list of validation issues, including which field failed and why.

This approach lets you handle errors gracefully without crashing the app.


Edge Cases in Zod Length Constraints

Whether you’re validating the length of a string, the number of items in an array, or setting range limits for numbers and dates, Zod’s .min() and .max() methods give precise control. The following sections explain how each data type handles these constraints with practical examples.

Strings:

const title = z.string().min(5, "Title must be at least 5 characters").max(50, "Title can be at most 50 characters");

const description = z.string().length(100, "Description must be exactly 100 characters");
  • In the example, title.parse("Hello Zod") passes because “Hello Zod” has 9 characters, which is within the (min)5–(max)50 character range.
  • The description.parse("A".repeat(100)) passes because the string is exactly 100 characters long, satisfying the .length(100) requirement.
  • If title were "Hey" (3 characters), Zod would immediately throw an error: "Title must be at least 5 characters".
  • Similarly, if description were shorter or longer than 100 characters, Zod would throw: "Description must be exactly 100 characters".
  • This demonstrates how Zod enforces length constraints in real data, not just as abstract rules.

Numbers:

const age = z.number().min(18, "Age must be at least 18").max(65, "Age cannot exceed 65");
  • In this example, age.parse(30) passes because the value is between the minimum of 18 and the maximum of 65.
  • If a user enters a number below 18 or above 65, Zod will immediately throw an error, indicating that the value violates the min or max constraint.
  • This demonstrates how Zod enforces numeric limits, ensuring the number adheres to both minimum and maximum rules, preventing invalid inputs and maintaining data integrity.

Arrays:

const scores = z.array(z.number().min(0, "Score cannot be less than 0").max(100, "Score cannot exceed 100")).length(5, "Scores array must contain exactly 5 numbers");

Explanation:

  • The scores array must contain exactly 5 numbers, enforced by the .length() constraint.
  • Each number in the array has a minimum value of 0 and a maximum value of 100.
  • If a number falls below the min or exceeds the max, Zod immediately throws an error for that specific element.
  • Similarly, if the array does not contain exactly 5 numbers, it fails validation, showing how Zod combines value-based constraints (min, max, minimum, maximum) with size-based constraints (length).
  • This ensures both the individual numbers and the array as a whole meet strict, predictable rules, maintaining consistent and valid numeric input.

Date:

const eventDate = z.date().min(new Date("2025-01-01"), "Date cannot be before Jan 1, 2025").max(new Date("2025-12-31"), "Date cannot be after Dec 31, 2025");

Explanation:

  • The .min() constraint ensures the date is not earlier than Jan 1, 2025.
  • The .max() constraint ensures the date is not later than Dec 31, 2025.
  • If a date falls outside this range, Zod throws a descriptive error.
  • This approach guarantees that date inputs adhere to a valid time frame, which is especially useful for scheduling, events, or age restrictions.

Length Constraints on Objects and Enums

Zod does not support .min(), .max(), or .length() directly on objects or enums.

In other words, length constraints are only meaningful for strings, numbers, arrays, and tuples, and attempting to apply them to objects or enums will result in an invalid schema.


Summary

Zod’s length constraints provide a robust way to enforce minimum, maximum, and exact size rules across strings, numbers, arrays, and dates. Using .min(), .max(), and .length(), developers can prevent invalid inputs like too-short passwords, overly long text, numbers outside allowed ranges, or arrays with the wrong number of elements.

For strings, these constraints ensure character counts are within the desired range. For numbers, .min() and .max() enforce value boundaries. Arrays can combine value-based and size-based rules, while dates can be restricted to specific timeframes.

It’s important to note that objects and enums do not support length constraints directly; validation for them must be handled at the field or value level.

Overall, Zod’s length constraints help maintain data consistency, security, and integrity, catching errors early and reducing the risk of invalid or unexpected input in your applications.

Length constraints are just one feature of Zod. For a full guide on schemas, validation methods, and working with different data types, explore Zod Schema Validation.

Sharukhan Avatar

Sharukhan Patan

Sharukhan Patan is the founder of Tecktol. He has worked as a software engineer specializing in full-stack web development.

Popular Posts