Numbers
Zod provides comprehensive number validation capabilities.
Basic Validation
ts
import { z } from "zod";
// Basic number validation
const numberSchema = z.number();
// Error messages during creation
const age = z.number({
required_error: "Age is required",
invalid_type_error: "Age must be a number",
});
Comparison Validation
ts
// Greater than/Less than
z.number().gt(5); // greater than 5
z.number().gte(5); // greater than or equal to 5 (alias: .min(5))
z.number().lt(5); // less than 5
z.number().lte(5); // less than or equal to 5 (alias: .max(5))
// Integer validation
z.number().int(); // must be an integer
// Range validation
z.number().min(0).max(100); // between 0 and 100
Special Number Validation
ts
// Positive/Negative
z.number().positive(); // > 0
z.number().nonnegative(); // >= 0
z.number().negative(); // < 0
z.number().nonpositive(); // <= 0
// Multiple validation
z.number().multipleOf(5); // must be divisible by 5 (alias: .step(5))
// Finite validation
z.number().finite(); // must not be Infinity or -Infinity
// Safe number validation
z.number().safe(); // must be between Number.MIN_SAFE_INTEGER and MAX_SAFE_INTEGER
Custom Error Messages
ts
z.number()
.int({ message: "Please enter an integer" })
.positive({ message: "Number must be positive" })
.max(100, { message: "Number must not exceed 100" });
// Combined validation example
const ageSchema = z.number()
.int({ message: "Age must be an integer" })
.min(0, { message: "Age cannot be negative" })
.max(120, { message: "Age cannot exceed 120" });
Type Coercion
ts
// Using coerce for type conversion
const numberSchema = z.coerce.number();
numberSchema.parse("123"); // => 123
numberSchema.parse(true); // => 1
numberSchema.parse(false); // => 0
numberSchema.parse("12.3"); // => 12.3
// Combined usage
const positiveInt = z.coerce.number()
.int({ message: "Must be an integer" })
.positive({ message: "Must be positive" });
positiveInt.parse("123"); // => 123
positiveInt.parse("-123"); // throws error: Must be positive
positiveInt.parse("12.3"); // throws error: Must be an integer