Whole-number input validation
Validate IDs, counts, indexes, or pagination values that must be whole numbers.
Zod · Module
z.int() defines a Zod schema for safe JavaScript integers. It accepts integer numbers within the safe range and rejects fractional, non-number, or unsafe values.
z.int() creates a schema for validating safe JavaScript integers. Parsing succeeds for integer inputs within the safe-integer range and fails for fractional, non-number, or unsafe integer values.
z.int()A Zod integer schema that parses safe integer numbers and reports validation errors for invalid input.
z.int() as the target schema when preprocessing input into an integer.z.int() narrows the accepted values to integers.z.int() instead of the older z.number().int() form.import { z } from "zod";
const schema = z.int();
console.log(schema.parse(42));
try {
schema.parse(3.14);
} catch (error) {
console.log("Invalid integer");
}Creates an integer schema, accepts 42, and rejects the non-integer 3.14.
Validate IDs, counts, indexes, or pagination values that must be whole numbers.
Combine preprocessing with integer validation when input arrives as text.
Use integer constraints in object schemas for request or configuration data.
z.int() validate?z.int() is a Zod schema that validates integer input and returns the parsed number when validation succeeds. It is intended for safe JavaScript integers rather than arbitrary numeric values.
Follow-up: How should unsafe integers be handled? They should be rejected or represented using a suitable alternative such as bigint, because JavaScript numbers outside the safe range can lose precision.
A fractional number does not satisfy the integer constraint, so parsing it produces a validation error. A value must also be a number and remain within JavaScript's safe-integer range.
Follow-up: What happens to an unsafe integer? It is not accepted by the current integer API, since values beyond the safe range can already have suffered rounding.
z.int() relate to z.number().int()?Zod's migration guidance recommends switching from z.number().int() to z.int(). The newer standalone declaration expresses the intended integer schema directly and enforces safe-integer behavior.
Follow-up: Why was the behavior changed? Unsafe numeric values can cause spontaneous rounding errors, so accepting them would not reliably validate the intended integer.
z.number()z.number().int()z.preprocess()z.coerce.number()