Make Zod.string() handle empty string as undefined

Having a schema like
z.string().min(4)
z.string().min(4)
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
Froxx
FroxxOP3y ago
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:
export const zString = (fieldName = "String") => z.string().min(1, { message: `${fieldName} is required` });
export const zString = (fieldName = "String") => z.string().min(1, { message: `${fieldName} is required` });
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
Piotrek
Piotrek3y ago
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
Piotrek
Piotrek3y ago
You can basically configure the error messages to your needs I've been using it for i18n but yeah
Froxx
FroxxOP3y ago
That might do it! Not sure yet how to implement my use case specifically, but I guess I'll figure it out. Thanks! love
bennettdev
bennettdev3y ago
I use a little helper with transform for this use case: https://gist.github.com/bennettdams/463c804fcfde0eaa888eaa4851c668a1
Gist
Zod empty string transformed to undefined including handling opti...
Zod empty string transformed to undefined including handling optional - validation.ts
Want results from more Discord servers?
Add your server