Optional email string schema fails on parsing empty string #2780
-
Well... I think it's working as expected that an empty string fails on In yup.string().email() // success with EMPTY STRING One possible workaround I can think of and is working: const emailSchema = z.string().max(0).or(z.string().email()); I mean.. although this works. but it's looking sooo weird... honestly. Is there any better alternative way to do so? Thanks. https://stackblitz.com/edit/stackblitz-starters-zfd4c9?file=index.js |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
Any updates on this one? |
Beta Was this translation helpful? Give feedback.
-
Considering 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 If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏 |
Beta Was this translation helpful? Give feedback.
Considering
optional
in TypeScript essentially just meansundefined
, it doesn't really make sence to me to allow an empty string. So I thinkzod
is doing the right thing here. I do understand it makes using things likereact-hook-form
a little more difficult. Here's how I would solve your use case: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…