z.number()
is a Zod schema method designed to validate numeric values, forming a fundamental part of the Zod schema system.
It ensures that data is properly typed as a number before being processed, stored, or sent through APIs.
Typical use cases include:
- Form inputs: Validate fields like age, quantity, or rating.
- API requests/responses: Ensure numeric data is received correctly in JSON payloads.
- Database storage: Prevent invalid or inconsistent numeric values from being saved.
z.number().parse(25);
Explanation:
z.number()
confirms that the input is numeric..parse()
checks the value and throws an error if it is not a valid number.
Now, let’s explore how to enforce more specific numeric rules with Zod.
Applying Numeric Range Rules
When working with numbers, it’s often necessary to restrict values to a certain range to maintain consistency and prevent errors.
By using Zod’s range methods, you can enforce minimum, maximum, or bounded values, avoiding problems like negative scores, excessive quantities, or out-of-range inputs.
z.number().min(1).max(100); // Number must be between 1 and 100
z.number().gte(10).lte(50); // Inclusive lower and upper bounds
For a more in-depth guide on range validation and numeric boundaries, check out our detailed Zod range guide.
Converting Non-Numbers with Zod Coercion
In real-world applications, numeric data may come as strings or other types. Zod’s coercion feature automatically converts these inputs to numbers, making validation simpler and safer.
z.coerce.number().parse("42"); // Converts to number 42
Learn more about handling various input types in our detailed Zod coercion guide.
Transforming Numbers After Validation
Sometimes numbers need post-processing, such as scaling, rounding, or formula-based adjustments. Zod’s .transform()
makes this easy:
z.number().transform(val => Math.round(val * 1.5)).parse(10); // Returns 15
Explore our Zod transform reference guide for more examples of numeric transformations.
Enforcing Specific Numeric Values with Literals
In certain cases, you may want to accept only one specific number, like 0
for off or 1
for active. Zod allows number literals for strict validation:
z.literal(5).parse(5); // Valid
z.literal(5).parse(6); // Error
Check our Zod literals reference guide for full examples across data types.
Summary
z.number()
provides robust validation for numeric inputs across forms, APIs, and databases. You can enforce numeric ranges, ensure integer values, and validate positive, negative, or finite numbers to maintain data consistency.
Coercion allows automatic conversion from strings or other types, while .transform()
lets you manipulate numbers after validation. When a number must match a specific value, number literals provide strict control over allowed inputs.