Sub topic 2
Your first schemas: strings, numbers, and booleans
This chapter assumes you can read basic TypeScript types, write ES module imports, and use try/catch. It also assumes you have a project with zod installed (npm install zod). The examples work on Zod 3 and Zod 4. Where the two versions differ, the text says so.
What a schema is
A Zod schema is a JavaScript value that describes what valid data looks like. You build it by calling functions on z, then use it to check a value while the program runs. A schema never changes at runtime. It is a reusable checker you create once and call many times.
The smallest schemas describe one primitive value: a string, a number, or a boolean.
import { z } from "zod";
const Name = z.string();
const Age = z.number();
const Active = z.boolean();
console.log(Name.safeParse("Ada").success); // true
console.log(Age.safeParse("36").success); // false
console.log(Active.safeParse(true).success); // truesafeParse takes any value and returns an object. Its success field says whether the value matched. The next chapters cover parse and safeParse in detail. Here we only use safeParse to look at results.
Note that Age.safeParse("36") fails. The string "36" looks like a number, but its type is string, and z.number() does not convert. Conversion is a separate feature called coercion, covered later in this tutorial.
How a schema checks a value
A schema runs in two stages. First it checks the base type. Then it runs each built-in check you chained onto it, in the order you wrote them. If the base type is wrong, the chained checks do not run.
flowchart TDThe diagram block below shows the flow.
This has a practical effect. If you pass 42 to z.string().min(3), you get one issue about the type and no issue about length. If you pass "ab", you get one issue about length.
String schemas
z.string() accepts any JavaScript string, including the empty string. Most real fields need more, so you chain checks onto it.
import { z } from "zod";
const Username = z
.string()
.trim()
.min(3, "Username must be at least 3 characters")
.max(20, "Username must be at most 20 characters")
.regex(/^[a-z0-9_]+$/, "Use lowercase letters, digits, and underscores only");
for (const input of ["ada_l", " ab ", "Ada Lovelace", 7]) {
const result = Username.safeParse(input);
if (result.success) {
console.log("ok:", JSON.stringify(result.data));
} else {
console.log(
"invalid:",
JSON.stringify(input),
result.error.issues.map((issue) => issue.message),
);
}
}Each check takes an optional second argument, a custom message. Without it, Zod uses a default message, and the default wording differs between Zod 3 and Zod 4. If your tests or UI depend on exact text, set your own messages.
Common string checks:
| Check | What it enforces |
|---|---|
| `.min(n)` / `.max(n)` | Length is at least or at most `n` characters |
| `.length(n)` | Length is exactly `n` |
| `.regex(re)` | The value matches a regular expression |
| `.startsWith(s)` / `.endsWith(s)` | The value begins or ends with the given text |
| `.includes(s)` | The value contains the given text |
| `.email()` / `.url()` / `.uuid()` | The value has the format of an email address, URL, or UUID |
| `.trim()` / `.toLowerCase()` | Reshape the value instead of rejecting it |
The last row matters. .trim() and .toLowerCase() do not check anything. They change the value, and the changed value is what result.data returns. In the Username example, " ab " is trimmed to "ab" first, so it then fails .min(3). Order is meaningful: put .trim() before .min() if you want length to ignore surrounding spaces.
Format checks are not proof
.email() checks that a string looks like an email address. It cannot tell you that the mailbox exists or that the user owns it. Likewise .url() accepts any string the URL parser accepts, including schemes such as javascript:. If you render user-supplied URLs as links, restrict the scheme yourself, for example with .refine (covered in a later chapter) or a .startsWith("https://") check.
Number schemas
z.number() accepts any JavaScript number except NaN. That rule rejects the result of a failed arithmetic operation such as Number("abc"), which is useful.
Infinity differs by version. Zod 3 accepts Infinity unless you add .finite(). Zod 4 rejects it by default. If your code must behave the same on both, add .finite() or .int(), since integers are always finite.
import { z } from "zod";
const Quantity = z.number().int().min(1).max(99);
const Price = z.number().positive().multipleOf(0.01);
const Rating = z.number().int().gte(1).lte(5);
console.log(Quantity.safeParse(3).success); // true
console.log(Quantity.safeParse(2.5).success); // false: not an integer
console.log(Quantity.safeParse(0).success); // false: below the minimum
console.log(Rating.safeParse(NaN).success); // false: NaN is never a number hereCommon number checks:
| Check | What it enforces |
|---|---|
| `.int()` | The value is a whole number |
| `.min(n)` / `.max(n)` | The value is at least or at most `n` (same as `.gte` / `.lte`) |
| `.gt(n)` / `.lt(n)` | The value is strictly greater or less than `n` |
| `.positive()` / `.nonnegative()` | Greater than 0, or 0 and above |
| `.negative()` / `.nonpositive()` | Less than 0, or 0 and below |
| `.multipleOf(n)` | The value is divisible by `n` |
JavaScript numbers are 64-bit floating-point values, so z.number().int() still cannot represent integers beyond Number.MAX_SAFE_INTEGER exactly. For larger values, Zod offers z.bigint(), which is outside this chapter.
Boolean schemas
z.boolean() accepts only true and false. It does not accept "true", 1, or "on".
import { z } from "zod";
const Flag = z.boolean();
for (const input of [true, false, "true", 1, null]) {
console.log(JSON.stringify(input), Flag.safeParse(input).success);
}
// true true
// false true
// "true" false
// 1 false
// null falseThis strictness catches a common bug. Query strings, environment variables, and HTML forms deliver booleans as text. A schema that quietly accepted "false" as a truthy string would let bad data through.
Exact values with literals
Sometimes a field must equal one specific value. z.literal describes that.
import { z } from "zod";
const Version = z.literal(2);
const Accepted = z.literal(true);
const Kind = z.literal("invoice");
console.log(Version.safeParse(2).success); // true
console.log(Version.safeParse(3).success); // false
console.log(Kind.safeParse("invoice").success); // trueLiterals become important when you combine them into discriminated unions in a later chapter.
Reading the result
Every safeParse call returns one of two shapes. If success is true, the result has a data field with the validated value. If success is false, it has an error field whose issues array lists each problem, with a path and a message.
import { z } from "zod";
const Port = z.number().int().min(1).max(65535);
const result = Port.safeParse(70000);
if (result.success) {
console.log("port", result.data);
} else {
for (const issue of result.error.issues) {
console.error(issue.code, issue.message);
}
}For a bare primitive, path is an empty array because there is no containing object. It becomes useful once schemas are nested inside objects, which the next chapter introduces.
TypeScript narrows the result type when you test result.success. Inside the if branch result.data is typed as number. Inside the else branch, result.error exists. Reading result.data without testing success is a compile error, which prevents you from using unvalidated data by accident.
Common mistakes
- Passing a numeric string to
z.number()and expecting it to pass. It fails by design. - Putting
.min()before.trim()and then being surprised that padded input counts toward the length. - Using
.email()or.url()as proof of ownership or safety. - Using
multipleOfwith decimals for money. - Assuming chained checks all run on a wrong-type input. Only the type issue is reported.
- Using
z.coerce.boolean()for text such as"false".
Exercise
Write a schema Coupon for a string that is trimmed, then must be exactly 8 characters long and match uppercase letters and digits only. Predict the result of Coupon.safeParse(" AB12CD34 ") and of Coupon.safeParse("ab12cd34").
Show answer
const Coupon = z.string().trim().length(8).regex(/^[A-Z0-9]+$/); The first input succeeds, because trim removes the spaces and leaves "AB12CD34", which has 8 characters and matches the pattern, so result.data is "AB12CD34". The second input fails with one issue from the regex check, because it has 8 characters but contains lowercase letters.
Exercise
A form sends the field quantity as the string "4". Does z.number().int().min(1).safeParse("4") succeed? Say why, and name the kind of feature you would need instead.
Show answer
No. The base type check fails first because the value is a string, so z.number() reports a type issue and the int and min checks do not run. You need coercion, which converts the string to a number before validating it.