-
What is the best way to handle optional fields? For example, consider the following form data
Even though both fields are marked as optional, the validation indicates that they are required. Code showing the behaviour is in this Gist. If I add default values |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
The const formData = zfd.formData({
num: zfd.numeric(z.number().optional()),
fruits: zfd.repeatableOfType(zfd.numeric(z.number().optional())),
}); This is because zod's 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:
When doing z.preprocess(
preprocessNumeric,
z.optional(
z.number()
)
)
// preprocess -> optional -> number |
Beta Was this translation helpful? Give feedback.
The
optional
has to go insidenumeric
. So the correct way to write that schema would be this way:This is because zod's
schema.optional()
is really just an alias forz.optional(schema)
. So when you dozfd.numeric().optional()
, that is essentially the same asSo in the scenario where the user leaves the number input blank, zod evaluates it like this:
num
is''
z.optional
gets evaluated first and sees that the value is not undefi…