skip to Main Content

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


  1. const z = require('zod');
    
    const regex1 = /[a-z]+/;
    const regex2 = /[0-9]+/;
    
    const schema = z.string().intersection(regex1, regex2);
    
    const validData = 'abc123';
    const invalidData = 'abc';
    
    console.log(schema.parse(validData)); // Output: 'abc123'
    console.log(schema.parse(invalidData)); // Throws ZodError
    

    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 the Zod.intersection method to combine the regex expressions into this schema. You can then use the parse 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.

    Login or Signup to reply.
  2. In your case I think you are looking for z.union to combine several z.string() schemas into a single schema. For example

    import { z } from 'zod';
    
    // Good to match the beginning and end of a string if you want the full string
    // to match
    const regexOne = /^1$/;
    const regexTwo = /^2$/;
    const regexThree = /^3$/;
    
    const s1 = z.string().regex(regexOne);
    const s2 = z.string().regex(regexTwo);
    const s3 = z.string().regex(regexThree);
    
    const schema = z.union([s1, s2, s3]);
    

    Documentation 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 using z.intersection for multiple regexes that must all match, you could also chain multiple class to .regex() after the base z.string() schema.


    Aside: I noticed in your question that you are attempting to call union directly on the schema returned by z.string() but as far as I can tell that method does not exist on ZodString. Nor is z.regex an exported schema from what I can see.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search