Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

parse() not picking up repetitions of the same error in an Array type #128

Closed
chrisapplegate opened this issue Aug 26, 2020 · 2 comments
Closed

Comments

@chrisapplegate
Copy link

chrisapplegate commented Aug 26, 2020

Hey there,

Big fan of this library's simplicity and flexibility. One thing I have noted however, is that parse() under-reports errors in an array, for items with the same key. Given the following code:

  const Shape = array(
    object({
      name: string().nonempty(),
      value: string().nonempty(),
    })
  );

  const data = [
    {
      name: "Name 1",
      value: "Value",
    },
    {
      name: "",
      value: "Value",
    },
    {
      name: "",
      value: "",
    },
  ];

  try {
    Shape.parse(data);
  } catch (e) {
    if (e instanceof ZodError) {
      console.log(e.errors);
    }
  }

I would expect three too_small errors to occur - on data[1].name, data[2].name and data[2].value. However, only two errors are reported:

[
  {
    "code": "too_small",
    "minimum": 1,
    "type": "string",
    "inclusive": true,
    "path": [
      1,
      "name"
    ],
    "message": "Should be at least 1 characters"
  },
  {
    "code": "too_small",
    "minimum": 1,
    "type": "string",
    "inclusive": true,
    "path": [
      2,
      "value"
    ],
    "message": "Should be at least 1 characters"
  }
]

Using Zod v 1.10.3.

I am not sure if this is a bug, or a feature - if it's the latter it isn't documented anywhere. It's clear from the above that data[2] is getting validated as value is being reported, but something is swallowing the error for its name.

My use-case btw is validating form data, and I have repeated rows of the same object shape, so having the error highlighted on every instance is the desired outcome.

If there is either a fix, or a workaround for this, that'd be very much appreciated. Thanks.

@chrisapplegate
Copy link
Author

As a follow-up, did a bit of dig through the source code and think it's related to this issue: #112 namely that the seen parameter being passed through is effectively caching the first item's name validation result, and returning that, so the second item's name never gets validated. Your comment on #112 that states you have a fix for this, any idea how that is coming along? Else I can supply a fix myself via PR.

@colinhacks
Copy link
Owner

Fixed in zod@1.11. Thanks for digging into this and providing such a detailed writeup!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants