Skip to content

Attach new global string validation functions directly to z.string() #366

Answered by colinhacks
jgoux asked this question in Q&A
Discussion options

You must be logged in to vote

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".

// customzod.ts;
export * from 'zod';
export const iban = ()=>z.string().refine(validateIban, { message: "Invalid IBAN" });
// server.ts
import * from "./customzod";
…

Replies: 1 comment 7 replies

Comment options

You must be logged in to vote
7 replies
@jgoux
Comment options

@colinhacks
Comment options

@DominikSerafin
Comment options

@colinhacks
Comment options

@DominikSerafin
Comment options

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