Make Zod.string() handle empty string as undefined
Having a schema like
I want
""
to throw Field X is required
and "abc"
to throw Field X must contain at least 4 characters
.
But I don't want to add this specifically to every prop.
Can I somehow make Zod handle ""
as "not defined" by default?5 Replies
I know I can do multiple .min concatenations like
z.string().min(1, {message: "required").min(4)
, but like I said, I would like to make zod behave like that in general, and not have to manually add the .min(1, ...)
-part to every prop
Fiddling around a bit more I found a little workaround by writing a custom extendable zod function:
With this instead of writing z.string(),min(4)
I can write zString().min(4)
.
Nevertheless I would still prefer using the vanilla one and have some kind of config / overload instead. So if anyone knows a way to do it that way, I would still appreciate it@Froxx I think that's what you're looking for: https://github.com/colinhacks/zod/blob/master/ERROR_HANDLING.md#customizing-errors-with-zoderrormap
GitHub
zod/ERROR_HANDLING.md at master · colinhacks/zod
TypeScript-first schema validation with static type inference - zod/ERROR_HANDLING.md at master · colinhacks/zod
You can basically configure the error messages to your needs
I've been using it for i18n
but yeah
That might do it!
Not sure yet how to implement my use case specifically, but I guess I'll figure it out.
Thanks!
I use a little helper with
transform
for this use case:
https://gist.github.com/bennettdams/463c804fcfde0eaa888eaa4851c668a1Gist
Zod empty string transformed to
undefined
including handling opti...Zod empty string transformed to
undefined
including handling optional - validation.ts