Input validation
Validate numeric fields from application input before using them in calculations or persistence.
Zod · Function
z.number() creates a Zod schema for finite numeric values. Chain numeric checks such as bounds, positivity, and divisibility to express stricter requirements.
Call z.number() to create a schema for numeric input. It accepts finite numbers, rejects NaN and infinities, and can be refined with numeric constraints such as bounds, positivity, and divisibility.
z.number()A Zod number schema that validates finite numbers and supports number-specific constraints.
import { z } from "zod";
const score = z.number().int().min(0).max(100);
console.log(score.parse(85));
// score.parse(85.5); // throws a validation error
// score.parse(Infinity); // throws a validation errorCreates an integer number schema restricted to the inclusive range 0 through 100, then parses a valid score.
Validate numeric fields from application input before using them in calculations or persistence.
Combine bounds and integer checks for values such as scores, counts, or quantities.
Require regular numeric intervals, such as prices or measurements divisible by a fixed increment.
z.number() constructs a schema that validates numeric values. The base schema accepts finite numbers and rejects NaN and Infinity.
Follow-up: How would you restrict values to positive integers? Chain the documented numeric constraints, for example z.number().int().positive().
Use gt or gte for lower bounds and lt or lte for upper bounds. The documentation identifies min as an alias for gte and max as an alias for lte.
Follow-up: How would you require a value from 1 through 10 inclusively? Use z.number().gte(1).lte(10), or the equivalent min and max aliases.
The number schema supports multipleOf for divisibility, with step as its alias. For example, z.number().multipleOf(5) accepts values evenly divisible by five.
Follow-up: How could this be combined with a range? Chain the divisibility constraint with bound methods, such as z.number().multipleOf(5).gte(0).lte(100).
z.intz.float32z.float64z.coerce.numberz.record