Skip to content

Optional email string schema fails on parsing empty string #2780

Answered by JacobWeisenburger
xsjcTony asked this question in Q&A
Discussion options

You must be logged in to vote

Considering optional in TypeScript essentially just means undefined, it doesn't really make sence to me to allow an empty string. So I think zod is doing the right thing here. I do understand it makes using things like react-hook-form a little more difficult. Here's how I would solve your use case:

const emailSchema = z.union( [
    z.literal( '' ),
    z.string().email(),
] )
console.log( emailSchema.safeParse( '' ).success ) // true
console.log( emailSchema.safeParse( '[email protected]' ).success ) // true
console.log( emailSchema.safeParse( 'foo' ).success ) // false

I know it's not as short as it would be with yup, but I think it's better to be verbose than to have a shorter syntax and not…

Replies: 2 comments 4 replies

Comment options

You must be logged in to vote
0 replies
Comment options

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

@JacobWeisenburger
Comment options

@shabbir-hossain132112
Comment options

@JacobWeisenburger
Comment options

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

This discussion was converted from issue #2513 on September 23, 2023 20:46.