Skip to content

How to handle optional fields in a zod schema? #83

Answered by airjp73
zayenz asked this question in Q&A
Discussion options

You must be logged in to vote

The optional has to go inside numeric. So the correct way to write that schema would be this way:

const formData = zfd.formData({
  num: zfd.numeric(z.number().optional()),
  fruits: zfd.repeatableOfType(zfd.numeric(z.number().optional())),
});

This is because zod's schema.optional() is really just an alias for z.optional(schema). So when you do zfd.numeric().optional(), that is essentially the same as

z.optional(
  z.preprocess(
    preprocessNumeric,
    z.number()
  )
)
// optional -> preprocess -> number

So in the scenario where the user leaves the number input blank, zod evaluates it like this:

  • Value for num is ''
  • z.optional gets evaluated first and sees that the value is not undefi…

Replies: 1 comment 4 replies

Comment options

You must be logged in to vote
4 replies
@zayenz
Comment options

@zayenz
Comment options

@airjp73
Comment options

@zayenz
Comment options

Answer selected by zayenz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants