zod icon indicating copy to clipboard operation
zod copied to clipboard

Union doesn't return all options issues when used with string-specific validation

Open moroine opened this issue 2 years ago • 2 comments

const { z } = require("zod")

const schema = z.union([z.string().startsWith("1"), z.string().startsWith("2")])
const result = schema.safeParse("3")
!result.success && console.log(result.error.issues)

Returns:

[
  {
    code: 'invalid_string',
    validation: { startsWith: '1' },
    message: 'Invalid input: must start with "1"',
    path: []
  }
]

Expected:

[
  {
    "code": "invalid_union",
    "unionErrors": [
      {
        "issues": [
          {
            code: 'invalid_string',
            validation: { startsWith: '1' },
            path: [],
            message: 'Invalid input: must start with "1"'
          }
        ],
        "name": "ZodError"
      },
      {
        "issues": [
          {
            code: 'invalid_string',
            validation: { startsWith: '2' },
            path: [],
            message: 'Invalid input: must start with "2"'
          }
        ],
        "name": "ZodError"
      }
    ],
    "path": [],
    "message": "Invalid input"
  }
]

Looks like it works when removing these lines: https://github.com/colinhacks/zod/blob/ae0f7a2c15e7741ee1b23c03a3bfb9acebd86551/src/types.ts#L2836-L2839

But I'm not sure what is dirty

moroine avatar Oct 02 '23 12:10 moroine

Looks like a duplicate of #2907

kouak avatar Jul 16 '24 09:07 kouak

Hi, @moroine. I'm Dosu, and I'm helping the Zod team manage their backlog. I'm marking this issue as stale.

Issue Summary:

  • The issue involves the zod library's union function not returning all validation errors for string-specific validations.
  • You suggested a potential fix but were unsure about the dirty variable's role.
  • @kouak mentioned this issue is a duplicate of issue #2907, which you acknowledged.

Next Steps:

  • Please confirm if this issue is still relevant to the latest version of the Zod repository. If so, you can keep the discussion open by commenting here.
  • Otherwise, this issue will be automatically closed in 7 days.

Thank you for your understanding and contribution!

dosubot[bot] avatar Jun 17 '25 16:06 dosubot[bot]