Sub topic 13
Coercing strings into numbers and dates
This chapter assumes you can write object schemas, call parse and safeParse, and read error.issues. It also assumes you know how JavaScript converts values with Number() and new Date().
Why coercion exists
Most data that crosses a boundary is text. Environment variables, URL query strings, HTML form fields, and path parameters are all strings. A schema such as z.number() rejects "42" because the value is a string, even though it looks like a number.
You have two options. You can parse the text yourself before validating, or you can let the schema do the conversion. Zod's z.coerce namespace does the second. Each coercing schema first converts the input with a built-in JavaScript function, then applies the usual checks.
| Schema | Conversion applied first | Then validates as |
|---|---|---|
| `z.coerce.string()` | `String(input)` | string |
| `z.coerce.number()` | `Number(input)` | number |
| `z.coerce.boolean()` | `Boolean(input)` | boolean |
| `z.coerce.bigint()` | `BigInt(input)` | bigint |
| `z.coerce.date()` | `new Date(input)` | valid date |
Every row in this table is a plain JavaScript conversion. If you know what Number(value) returns for a given value, you know what z.coerce.number() accepts.
Coercing numbers
Here is a schema for the query string of a paginated list endpoint.
import { z } from "zod";
const Query = z.object({
page: z.coerce.number().int().min(1).default(1),
pageSize: z.coerce.number().int().min(1).max(100).default(20),
});
console.log(Query.parse({ page: "3" }));
// { page: 3, pageSize: 20 }
const bad = Query.safeParse({ page: "abc" });
if (!bad.success) {
console.log(bad.error.issues[0].path, bad.error.issues[0].message);
}"3" becomes 3, and .int() and .min(1) then check the number. pageSize is missing, so default(20) supplies it. "abc" becomes NaN, which Zod rejects, so the failure shows up as an ordinary issue at the path ["page"]. You handle it the same way as any other validation error.
Values that coerce more than you expect
Number() is permissive. The conversions below are legal in JavaScript, so z.coerce.number() accepts them:
Number("")is0, so an empty form field passes as zero.Number(" 12 ")is12, because whitespace is trimmed.Number(null)is0andNumber(true)is1.Number("0x1f")is31andNumber("1e3")is1000.Number(undefined)isNaN, so a missing key fails.
The empty string is the case that causes real bugs. A user who leaves "age" blank gets 0 and no error. To reject blanks, validate the text first and then pipe it into the coercion.
import { z } from "zod";
const NumberFromText = z
.string()
.trim()
.min(1, "Required")
.pipe(z.coerce.number().int().nonnegative());
console.log(NumberFromText.safeParse("").success); // false
console.log(NumberFromText.safeParse(" 42 ").data); // 42
console.log(NumberFromText.safeParse("4.5").success); // falsepipe feeds the output of the first schema into the second. The string schema guards the text and the number schema guards the value. This also tightens the input: non-strings such as null or true now fail at the z.string() step, where plain z.coerce.number() would have converted them.
Coercing dates
z.coerce.date() calls new Date(input) and rejects the result if it is an Invalid Date.
import { z } from "zod";
const Range = z.object({
from: z.coerce.date(),
to: z.coerce.date().optional(),
});
const parsed = Range.parse({ from: "2026-01-15" });
console.log(parsed.from instanceof Date); // true
console.log(parsed.from.toISOString()); // 2026-01-15T00:00:00.000Z
console.log(Range.safeParse({ from: "next tuesday" }).success); // falseThe output is a real Date object, so the inferred type of from is Date. Three details matter:
- A date-only ISO string such as
"2026-01-15"is read as UTC midnight. A date-time string without an offset, such as"2026-01-15T10:00:00", is read in the machine's local time zone. If your inputs mix both forms, results can differ between servers. - A number is treated as milliseconds since the epoch, so
1700000000means a moment in January 1970, not 2023. Seconds-based timestamps need to be multiplied by 1000 first. nullbecomes the epoch (new Date(null)), so it is accepted as 1 January 1970.undefinedbecomes an invalid date and fails.
If you want strict ISO validation but still want a Date at the end, check the string before you convert it.
import { z } from "zod";
const IsoDate = z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/, "Use YYYY-MM-DD")
.pipe(z.coerce.date());
console.log(IsoDate.safeParse("2026-03-09").success); // true
console.log(IsoDate.safeParse("03/09/2026").success); // falseThe boolean trap
z.coerce.boolean() uses Boolean(input), and every non-empty string is truthy in JavaScript.
import { z } from "zod";
console.log(z.coerce.boolean().parse("false")); // true
console.log(z.coerce.boolean().parse("0")); // true
console.log(z.coerce.boolean().parse("")); // falseThe string "false" becomes true. For text flags, list the values you accept and transform them yourself. This is the pattern used for DEBUG in the environment-variable example from the plan of this tutorial.
import { z } from "zod";
const Flag = z
.enum(["true", "false", "1", "0"])
.transform((value) => value === "true" || value === "1");
console.log(Flag.parse("false")); // false
console.log(Flag.parse("1")); // true
console.log(Flag.safeParse("yes").success); // falseAnything outside the list produces an issue instead of a silent guess. Newer Zod 4 releases also ship z.stringbool() for this job. Check which version your project uses before relying on it.
Coercion on real boundaries
Query strings and form submissions are the most common sources. Both can be turned into a plain object of strings with Object.fromEntries, and the schema does the rest.
import { z } from "zod";
const Filters = z.object({
page: z.coerce.number().int().min(1).default(1),
since: z.coerce.date().optional(),
archived: z.enum(["true", "false"]).default("false").transform((v) => v === "true"),
});
const params = new URLSearchParams("page=2&since=2026-02-01&archived=true");
const filters = Filters.parse(Object.fromEntries(params));
console.log(filters.page); // 2
console.log(filters.since); // Date for 2026-02-01
console.log(filters.archived); // trueEnvironment variables work the same way with process.env. A FormData object can be handled with Object.fromEntries(formData), but remember that file inputs yield File objects and repeated keys keep only the last value.
Types of coercing schemas
z.infer gives you the output type, which is number for z.coerce.number() and Date for z.coerce.date(). The input type depends on the Zod version. In Zod 3, the input type of a coercing schema is still number or Date, even though it accepts strings at runtime. In Zod 4, the input type is unknown, which describes the runtime behavior more honestly. If you need an input type that says "string", use the z.string().pipe(...) form shown above, and z.input will report string.
import { z } from "zod";
const PageText = z.string().pipe(z.coerce.number());
type In = z.input<typeof PageText>; // string
type Out = z.output<typeof PageText>; // numberCommon mistakes
- Using
z.coerce.number()on optional fields without.optional()or.default(). A missing key becomesNaNand fails. - Letting an empty string through as
0. Guard withz.string().trim().min(1).pipe(...). - Using
z.coerce.boolean()for"true"and"false"text. - Coercing JSON bodies, which hides type errors from clients.
- Assuming date-only and date-time strings share one time zone.
Exercise
A query string contains limit= (the key is present with an empty value). Your schema is z.coerce.number().int().min(1).max(50). What does parse do with { limit: "" }, and how do you change the schema so a blank limit is reported as an error?
Show answer
Number("") is 0, so the value coerces to 0 and then fails .min(1). The failure message is about the minimum, not about a blank field. To report the blank explicitly, validate the text first: z.string().trim().min(1, "Required").pipe(z.coerce.number().int().min(1).max(50)). The empty string now fails at the min(1) check on the string, with the message "Required".
Exercise
What does z.coerce.boolean().parse("false") return, and what schema would you use to read an environment variable FEATURE_X that must be exactly "true" or "false"?
Show answer
It returns true, because Boolean("false") is true for any non-empty string. Use z.enum(["true", "false"]).transform((value) => value === "true"), which returns a real boolean and rejects any other text.