-
I'm trying to figure out how to get optional number inputs to work with Zod and react-hook-form. On the resolvers README, we have this:
When validating if the input is empty, I get the "Expected number, received nan" error. This occurs regardless of if I modify the schema to have I even tried adding in What is the intended way to handle optional numeric inputs? How do I interact with that error? CodeSandbox: https://codesandbox.io/s/react-hook-form-number-input-error-c0cbs?file=/src/App.tsx |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 13 replies
-
share a codesandbox. |
Beta Was this translation helpful? Give feedback.
-
The reason you get There is an option on register called z.object({
age: z.number().optional(),
});
<input
type="number"
{...register("age", {
setValueAs: (v) => v === "" ? undefined : parseInt(v, 10),
})}
/>; |
Beta Was this translation helpful? Give feedback.
-
Hi. I used coerce together with optional() and it works |
Beta Was this translation helpful? Give feedback.
-
This work for me: suits: z.preprocess((value) => {
if (value === "") return undefined;
return Number(value);
}, z.union([z.number().int().positive().min(1), z.nan()]).optional()), |
Beta Was this translation helpful? Give feedback.
The reason you get
NaN
@henryjin3 is becausevalueAsNumber
returns NaN if something goes wrong (from the register documentation). And something goes wrong because the input field is returning a string, something I learned in #7128.There is an option on register called
setValueAs
which let us define our own transform function that will be called before validation.