ZodValidationError Fix2026 Updated

Zod Optional Field Not Working— .optional() vs .nullable() [Fixed 2026]

Also covers: empty string validation · .default() · TypeScript inference · .nullish() · schema.partial() for PATCH

January 20265 min readZod v3 · TypeScript

⚡ Common Mistakes

Error
// Fails for empty string — empty string is not undefined
z.string().optional().parse("")   // ZodError: expected string, got undefined?
// No — empty string "" passes .optional() — but min() or email() will reject it

// Wrong modifier — null vs undefined confusion  
z.string().optional().parse(null)   // ZodError — null is not undefined
z.string().nullable().parse(null)   // ✅ null is allowed

✅ Quick reference

optional vs nullable vs nullish
z.string().optional()    // string | undefined — field can be absent
z.string().nullable()    // string | null      — field must exist, can be null
z.string().nullish()     // string | null | undefined — both missing and null ok

optional() vs nullable() vs nullish()

Zod has three distinct modifiers for handling absent/empty values. Choosing the wrong one is the most common source of optional field bugs: .optional() allows undefined (field absent), .nullable() allows null (field present but null), and .nullish() allows both.

1

Use .optional() for Fields That May Be Absent

Field is undefined when not provided
2 min
When to use each modifier
import { z } from "zod"

const profileSchema = z.object({
  // Required — must be present and valid
  username: z.string().min(3),

  // Optional — field can be completely absent (undefined)
  bio: z.string().max(500).optional(),

  // Nullable — field must be present but can be null (common for DB columns)
  avatarUrl: z.string().url().nullable(),

  // Nullish — field can be missing or explicitly null
  lastSeenAt: z.date().nullish(),
})

// TypeScript types produced:
// username:    string
// bio:         string | undefined
// avatarUrl:   string | null
// lastSeenAt:  Date | null | undefined

// ✅ All pass:
profileSchema.parse({ username: "alice" })                      // bio absent — ok
profileSchema.parse({ username: "alice", bio: undefined })      // bio explicit undefined — ok
profileSchema.parse({ username: "alice", avatarUrl: null })     // null avatar — ok

// ❌ Fails:
profileSchema.parse({ username: "alice", bio: null })           // null not allowed for optional
2

Fix Empty String Failing Optional String Validation

HTML form empty inputs come through as empty strings not undefined
3 min

HTML form fields submit empty strings when blank — not undefined. .optional() allows undefined but still validates the string if present. An empty string with .min(1) still fails.

Handle empty strings from HTML forms
// ❌ z.string().optional() still rejects empty string via .email() or .min()
const schema = z.object({
  email: z.string().email().optional(),   // "" fails .email() even with .optional()
})
schema.parse({ email: "" })  // ZodError: Invalid email

// ✅ Option A — convert empty string to undefined with transform
const schema = z.object({
  email: z.string().email().optional().or(z.literal("")).transform(v => v || undefined),
})

// ✅ Option B — allow empty or valid email
const optionalEmail = z.union([
  z.string().email("Invalid email"),
  z.literal(""),
]).optional().transform(v => v === "" ? undefined : v)

// ✅ Option C — preprocess to convert "" to undefined before validation
const optionalString = z.preprocess(
  val => (val === "" ? undefined : val),
  z.string().optional()
)

// ✅ Most practical — use in form schema
const contactSchema = z.object({
  name: z.string().min(1, "Name required"),
  phone: z.preprocess(
    val => (val === "" ? undefined : val),
    z.string().regex(/^+?[ds-]{10,}$/, "Invalid phone").optional()
  ),
})
3

Add Default Values to Optional Fields

.default() — field is optional but always has a value after parse
2 min
.default() — provide fallback when field is absent
const settingsSchema = z.object({
  theme: z.enum(["light", "dark", "system"]).default("system"),
  language: z.string().default("en"),
  notifications: z.boolean().default(true),
  pageSize: z.number().min(5).max(100).default(20),
})

// All fields optional in input — defaults fill in missing values
settingsSchema.parse({})
// → { theme: "system", language: "en", notifications: true, pageSize: 20 }

settingsSchema.parse({ theme: "dark" })
// → { theme: "dark", language: "en", notifications: true, pageSize: 20 }

// TypeScript type after .default():
type Settings = z.infer<typeof settingsSchema>
// { theme: "light" | "dark" | "system", language: string, ... }
// Note: with .default(), the type is NOT | undefined — default ensures a value always exists
4

Handle Optional Fields in TypeScript

TypeScript undefined type for optional Zod fields
2 min
TypeScript patterns for optional Zod fields
import { z } from "zod"

const userSchema = z.object({
  id: z.string(),
  name: z.string(),
  bio: z.string().optional(),        // bio?: string | undefined
  role: z.enum(["admin", "user"]).default("user"),  // role: "admin" | "user"
})

type User = z.infer<typeof userSchema>
// { id: string, name: string, bio?: string | undefined, role: "admin" | "user" }

// Handle optional field in code:
function displayUser(user: User) {
  const bio = user.bio ?? "No bio provided"   // nullish coalescing
  console.log(user.name, bio)
}

// Optional with transform — convert to null for DB storage
const dbUserSchema = userSchema.transform(data => ({
  ...data,
  bio: data.bio ?? null,    // convert undefined to null for DB nullable column
}))

type DbUser = z.infer<typeof dbUserSchema>
// { ..., bio: string | null, role: "admin" | "user" }
5

Partial Schemas for PATCH Requests

PATCH endpoint — all fields optional for partial updates
2 min
schema.partial() for PATCH API endpoints
import { z } from "zod"

// Full creation schema — all fields required
const createUserSchema = z.object({
  name: z.string().min(2),
  email: z.string().email(),
  role: z.enum(["admin", "user"]),
  bio: z.string().max(500),
})

// PATCH schema — all fields optional (partial update)
const updateUserSchema = createUserSchema.partial()
// Equivalent to: z.object({ name?: ..., email?: ..., role?: ..., bio?: ... })

// Partial only specific fields — keep some required
const partialUpdateSchema = createUserSchema.partial({
  bio: true,    // bio optional
  role: true,   // role optional
})
// name and email still required, bio and role optional

// API route usage:
export async function PATCH(request: Request, { params }: { params: { id: string } }) {
  const body = await request.json()
  const result = updateUserSchema.safeParse(body)
  if (!result.success) return Response.json({ errors: result.error.flatten().fieldErrors }, { status: 422 })

  const updated = await db.user.update({
    where: { id: params.id },
    data: result.data,   // only the provided fields are updated
  })
  return Response.json(updated)
}

Prevention

Frequently Asked Questions

What is the difference between Zod optional and nullable?+
.optional() allows the value to be undefined (field can be absent). .nullable() allows the value to be null (field must be present but can be null). .nullish() allows both undefined and null. In HTML forms, absent fields come through as undefined; database nullable columns come through as null.
Why does my Zod optional field fail when the input is an empty string?+
An empty string is not undefined — it is a valid string value. Zod's z.string().optional() allows undefined but still requires the string to be valid if present. To allow empty strings, add .or(z.literal('')) or use .transform(v => v === '' ? undefined : v) to convert empty strings to undefined.
How do I set a default value for a Zod optional field?+
Use .default(value) — it provides a value when the input is undefined. For example: z.string().default('user') means if the field is absent, the parsed value will be 'user'. The TypeScript type becomes string (not string | undefined) because a default is always provided.
What TypeScript type does Zod optional() produce?+
z.string().optional() produces string | undefined in TypeScript. z.string().nullable() produces string | null. z.string().nullish() produces string | null | undefined. Use z.infer<typeof schema> to get the exact TypeScript type from your Zod schema.
How do I make all fields optional for a PATCH request?+
Use schema.partial() to create a new schema where all fields are optional. For example: const updateSchema = createSchema.partial() produces a schema where every field is optional. This is the standard pattern for PATCH endpoints where you only update the provided fields.
Can I mix required and optional fields in the same Zod schema?+
Yes. Define each field independently — z.string() for required, z.string().optional() for optional. Only the fields marked with .optional() can be omitted. You can also use schema.partial(['field1', 'field2']) to make only specific fields optional while keeping others required.

Need Expert Help?

We Build Type-Safe Validation with Zod

Softplix engineers implement end-to-end type-safe validation with Zod for forms, APIs, and Server Actions. Let us help.

Talk to an Engineer