Attach new global string validation functions directly to z.string() #366
-
Hello all, Is it possible to extend z.string() to add other string validation functions in the vein as the built-in uuid and email functions? Something like This would be very handy for validations that are common across the codebase and to handle i18n on the error message. I know I could use refinement but it's not convenient for often used validation rules. I made a special ErrorMap for i18next and it would automatically be handled by this case : https://gist.github.com/jgoux/720f011a4428e64f50bebc9938219518#file-zod-ts-L60-L68 I'm currently using the v3 in alpha. 😄 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
The best part (in my opinion) of v3 is that anyone can define their own schema classes by simply subclassing Besides Alternatively consider using the "re-export pattern". // customzod.ts;
export * from 'zod';
export const iban = ()=>z.string().refine(validateIban, { message: "Invalid IBAN" });
That custom error map looks really great! If you think that would be useful for other people, consider publishing it to NPM and I'll link to it on the README. |
Beta Was this translation helpful? Give feedback.
The best part (in my opinion) of v3 is that anyone can define their own schema classes by simply subclassing
ZodType
. In your case, you could directly subclass ZodString and add these methods yourself. It wouldn't be super difficult, just look at the ZodString implementation to see how it works.Besides
iban
what methods are you looking to add? I might be amenable to adding them to core. I'm a little surprised I don't get more requests for other string validation methods.Alternatively consider using the "re-export pattern".