Optional and Nullable Fields
You'll learn how to handle fields that might not exist, might be null, or might be undefined in your Zod form schemas.
The Three Similar But Different Modifiers
In form validation, not every field is required. Zod gives you three ways to express "this field might not have a value":
.optional()– The field can beundefinedor omitted entirely.nullable()– The field can benull(but must be present in the object).nullish()– The field can beundefined,null, OR omitted (combines both)
Think of it like optional questions on a survey: .optional() means you can skip the question, .nullable() means you must acknowledge it but can answer "N/A," and .nullish() accepts either approach.
When to Use Each
const formSchema = z.object({
middleName: z.string().optional(), // User might not have one
phoneNumber: z.string().nullable(), // Explicitly set to null when cleared
bio: z.string().nullish(), // Maximum flexibility
});
.optional() is most common for form fields users genuinely don't need to fill. The field won't be in the submitted data if left blank.
.nullable() works when your API explicitly uses null to represent "no value" versus the field being absent. Common with database integrations.
.nullish() is your safety net when you're unsure whether the data source will send undefined or null for empty values—it accepts both.
Combining with Other Validations
You can still add constraints to optional fields:
age: z.number().min(0).optional() // If provided, must be positive
Key Takeaway: Use .optional() for skippable fields, .nullable() when your API uses explicit null values, and .nullish() when you need to accept both undefined and null gracefully.