Skip to content

Zod and optional number inputs #6980

Answered by Sti2nd
mtnowl asked this question in Q&A
Nov 4, 2021 · 4 comments · 13 replies
Discussion options

You must be logged in to vote

The reason you get NaN @henryjin3 is because valueAsNumber 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.

z.object({
  age: z.number().optional(),
});

<input
  type="number"
  {...register("age", {
    setValueAs: (v) => v === "" ? undefined : parseInt(v, 10),
  })}
/>;

Replies: 4 comments 13 replies

Comment options

You must be logged in to vote
1 reply
@mtnowl
Comment options

Comment options

You must be logged in to vote
2 replies
@bryanprimus
Comment options

@itujono
Comment options

Answer selected by bluebill1049
Comment options

You must be logged in to vote
10 replies
@kellyrmilligan
Comment options

@hatchli
Comment options

@its-monotype
Comment options

@henokyehulu
Comment options

@enfroz
Comment options

Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet