Why Your Zod Validation Fails Before It Even Runs (And How to Fix It)

Published: (June 11, 2026 at 04:43 AM EDT)
2 min read
Source: Dev.to

Source: Dev.to

Cover image for Why Your Zod Validation Fails Before It Even Runs (And How to Fix It)

              [![mohammad rostami](https://media2.dev.to/dynamic/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3628004%2F2099a6d6-913c-4088-ba3c-9b587f8b8fd4.jpg)](https://dev.to/mohammad_rostami_)
              
              
            
      

      
            

If you’re using Zod with react-hook-form, you’ve probably seen this at least once:

Invalid input: expected number, received NaN

At first glance, it looks like a simple validation issue.

It’s not.

The real problem

When working with form inputs:

All values come in as strings

z.coerce.number() tries to convert them Empty input ("") or invalid values → NaN

And here’s the catch:

Zod fails before your .min() / .max() validations run.

So instead of your custom message, you get a generic (and not very helpful) error.

It gets trickier

If you’re using TypeScript:

z.inputz.output

react-hook-form works with the input type

Zod gives you the output type after parsing

This mismatch can lead to confusing type errors and wrong assumptions about your data.

The fix

You need to handle invalid input before Zod tries to validate it:

readTime: z.preprocess((val) => {
  if (val === "" || val === undefined) return undefined;

  const num = Number(val);
  return isNaN(num) ? undefined : num;
},
z.number()
  .min(2, 'Minimum read time is 2 minutes')
  .max(60, 'Maximum read time is 60 minutes')
)
Enter fullscreen mode


Exit fullscreen mode

What this solves

  • Empty input → handled properly

  • Invalid numbers → no more NaN issues

  • Custom validation messages → actually shown

  • Cleaner UX overall

    Takeaway

If you’re using z.coerce.number() in forms, don’t rely on it blindly.

Always normalize your input first.

Because sometimes the bug isn’t in your validation rules…

it’s in how your data arrives before validation even starts.

0 views
Back to Blog

Related posts

Read more »

The spec is in the wrong place

My day job is at a large tech company. Hundreds of engineering teams, and every one of them is somewhere different on AI adoption. Some are still treating codin...

The Heuristics Say Don't

A culture that only records its disasters ends up with a biased archive. Wars documented, plagues chronicled, collapses catalogued. The quiet decades go unwritt...