Number and Date Validations
You'll learn how to use Zod's specialized constraints for number and date form fields to catch invalid inputs before they reach your backend.
The Core Idea
While string validation handles text, many forms need numeric ranges (age, quantity, price) or date boundaries (birth dates, deadlines). Zod provides built-in methods specifically for these data types that feel natural to use.
Number Validation Constraints
After defining a number field with z.number(), you chain specific rules:
const schema = z.object({
age: z.number()
.int() // Must be an integer (no decimals)
.positive() // Must be > 0
.min(18) // At least 18
.max(120), // Not more than 120
price: z.number()
.positive() // No negative prices
.multipleOf(0.01) // Rounds to cents
});
The analogy: Think of these as guardrails on a bowling lane—each constraint prevents the ball (your data) from going somewhere invalid.
You can also use .nonnegative() (>= 0), .negative() (< 0), and .nonpositive() (<= 0) as needed.
Date Validation
Zod treats dates as special objects with time-based constraints:
const eventSchema = z.object({
birthDate: z.date()
.max(new Date()), // Can't be in the future
eventStart: z.date()
.min(new Date()), // Must be today or later
deadline: z.date()
.min(new Date("2024-01-01"))
.max(new Date("2024-12-31"))
});
These constraints compare actual Date objects, making "must be after today" or "before year 2000" trivial to express.
Key Takeaway: Zod's .int(), .positive(), .min(), .max() for numbers and .min(), .max() for dates give you type-safe, declarative validation for specialized form inputs—catching bad data before submission with clear, chainable rules.