I have something like this:
const regexOne = <regex>
const regexTwo = <regex>
const regexThree = <regex>
const Schema = z.object({
validation: z.string().toUpperCase().union([z.regex(regexOne), z.regex(regexTwo), z.regex(RegexThree)])
})
But I am not having success. Any suggestions on how I can validate data from an input using either one of the regex expressions?
I tried also separating 3 different schemas, each one with one regex rule. But I had no success yet.
2
Answers
Yes, it’s possible to validate data against multiple regex expressions using Zod. To achieve this, you can use the
Zod.intersection
method to combine the regex expressions into a single schema.First, define the regex expressions you want to use in the validation process. Then, create a
Zod.string()
schema and use theZod.intersection
method to combine the regex expressions into this schema. You can then use theparse
method to validate the data against the schema.If the provided data passes all the checks defined in the schema, the parse method returns the validated data. If the data fails any of the checks, a ZodError will be thrown.
In your case I think you are looking for
z.union
to combine severalz.string()
schemas into a single schema. For exampleDocumentation on
z.union
Another answer mentioned using
z.intersection
which is the alternative option.z.union
will succeed if one of the regexes matches.z.intersection
will succeed only if all regexes match. Rather than usingz.intersection
for multiple regexes that must all match, you could also chain multiple class to.regex()
after the basez.string()
schema.Aside: I noticed in your question that you are attempting to call
union
directly on the schema returned byz.string()
but as far as I can tell that method does not exist onZodString
. Nor isz.regex
an exported schema from what I can see.