colinhacks/zod

[suggestion] regex validation errors should include the pattern

Opened this issue · 3 comments

If I have a schema with a .regex(), and attempt to parse an invalid value:

const SomeSchema = z.string().regex(/^[a-z]+$/);
SomeSchema.parse('abc3');

The error I get looks like this:

ZodError: [
  {
    "validation": "regex",
    "code": "invalid_string",
    "message": "Invalid",
    "path": []
  }
]

It would be very nice if this error included a way to get the pattern which failed, like so:

ZodError: [
  {
    "validation": "regex",
    "pattern": /^[a-z]+$/,
    "code": "invalid_string",
    "message": "Invalid",
    "path": []
  }
]

or something like that - maybe errors can start including the zod schema it relates to, so that I can infer these things myself.

ZodError: [
  {
    "validation": "regex",
    "code": "invalid_string",
    "message": "Invalid",
    "path": [],
    "schema": ...
  }
]

I can currently get around this like so:

const regexRefine = (regex: RegExp) =>
  [
    (data: string) => regex.test(data),
    `String does not match regex ${regex}`,
  ] as const;
const SomeSchema = z.string().refine(...regexRefine(/^[a-z]+$/));

Actually, this is way better:

const regexWithPatternInError = (regex: RegExp): [RegExp, string] =>
  [regex, `String does not match pattern "${regex}"`] as const;
const SomeSchema = z.string().regex(...regexWithPatternInError(/^[a-z]+$/));

but the issue still stands

There's another way to get the regex which might be useful for some cases:

declare const stringSchema: z.ZodString;

const regex = stringSchema._def.checks.find(c => c.kind === "regex")?.regex;

Right, but unfortunately the ZodError doesn't include the schema that failed, so I'm unable to even inspect the schema