Validating optional text inputs
See original GitHub issueConsidering an optional email text input: from user perspective I think the appropriate validation for this would be z.string().email().optional()
which allows either undefined
or a valid email.
In React
, these types of inputs are almost never undefined. In fact, optional fields are considered empty strings.
What is the common way to achieve validating these type of fields correctly with zod? I have tried things like z.union([z.string().email, z.literal('')])
or refine
, which felt a little unintuitive for a simple, yet very common optional field value.
I was hoping for either a configurable optional
type that could allow empty strings as well or a dedicated empty type for a string.
Anyway, thank you for this great validation library, happy to help in any way!
Issue Analytics
- State:
- Created 3 years ago
- Reactions:17
- Comments:10 (1 by maintainers)
Top GitHub Comments
@glennreyes I understand the feeling that this is strangely convoluted. But the source of that convolution is the messy, chaotic behavior of web forms. Zod provides a rigorous, consistent way of defining types, so it can be complex to represent weird edge cases like those surfaced by poorly designed web standards 🤷♂️ I think implementing a new method or overloading
.optional
to allow for empty strings isn’t necessary given that there are already multiple ways to implement this, but I understand the feeling.Will some of the recent developments in TS surrounding tuples and rest parameters, it will shortly be possible to chain together calls to
.or()
that let you build up unions piece by piece. This isn’t implemented yet but here’s what it’ll look like:Which I think looks and feels a lot nicer than the
z.union
or refinement approaches.But for now the approaches described by you and @jasonadkison are the right way to go. Because Zod is composable, you only have to define that schema once, then you can import it wherever you’re defining forms.
This thread is strangely tone deaf to an extremely common and obvious use-case, validating forms. Not sure how requiring copious boilerplate to make
optional
work improveszod
or anything else.I appreciate, maybe, preserving the sanctity of bare
optional()
, but can we have something likeoptional({allowEmpty:true})
?