Fixing Custom Zod Error Messages Not Showing in React Hook Form


If you’ve ever worked with React forms, you know how frustrating it is when your custom validation messages don’t show up as expected.
I ran into a similar situation while using React Hook Form with Zod and Shadcn UI. Even after writing my custom error messages in the Zod schema, the form would only display “Required” on the UI.
This is what it looks like in practice:
In the case of that particular “AddressLine1” field, you probably defined your Zod schema (like I did):
or like this:
addressLine1: z.string().nonempty("Addressline1 is required"),
You then used <FormMessage />
In your form field, expecting the message “Addressline1 is required” to appear, instead, you see “Required” or nothing at all on the UI.
The reason it happens:
React Hook Form needs every form field to start with a value. If you don’t set a default value for a field, it will be undefined
by default. Zod’s .nonempty()
and .min(1)
checks are only triggered if the value is a string, even if it’s an empty string. So if the string value is undefined
Zod won’t use your custom message. Instead, it’ll give a generic “Required” or “invalid_type” error, because it expected a string but got undefined
.
To fix it….
Always set default values for your fields in the useForm
hook:
Now, the field always starts as an empty string, so Zod will trigger your .nonempty("Addressline1 is required")
message when the field is left blank.
With these default values set to empty strings, Zod receives the correct data type and can apply your custom validation messages. If you leave a field blank and submit, your message will display exactly as you wrote it.
Subscribe to my newsletter
Read articles from Michael Ugorji directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Michael Ugorji
Michael Ugorji
A Frontend Developer skilled at building dynamic, functional and mobile responsive webapps using HTML, CSS, JavaScript, and ReactJS. Outside of development, I love writing. And I am passionate about writing content focused on The Metaverse, NFTs, Blockchain Technology, Decentralized Finance, and the Web 3.0 space in general.