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

Create exact error message for z.array().length(). #1611

Closed
john-schmitz opened this issue Nov 28, 2022 · 3 comments · Fixed by #1620
Closed

Create exact error message for z.array().length(). #1611

john-schmitz opened this issue Nov 28, 2022 · 3 comments · Fixed by #1620

Comments

@john-schmitz
Copy link
Contributor

Given this schema:

const testSchema = z.array(z.number()).length(4);

For arrays with less than 4 elements, it returns the message:

Should have at least 4 items

For arrays with more than 4 elements, it returns the message:

Should have at most 4 items

I wish instead for it to return a message explaining that it should be precisely 4 items:

Should have exactly 4 items

I know I could achieve that with a custom refine validation, but it would be nice to have it baked in.

Of course, if you find this suggestion valid, I could make a PR for it.

@maxArturo
Copy link
Contributor

Hi @john-schmitz ! I'll provide my opinion based on what I see implemented. Here's the def for z.array().length()

  length(len: number, message?: errorUtil.ErrMessage): this {
    return this.min(len, message).max(len, message) as any;
  }

That's why you see the behavior described in your issue - min gets validated before max, and their respective messages get shown in the validation result. I believe building an exactly out of min and max is probably the way to do it (keeping in with the don't-repeat-yourself ethos).

However, there's an opportunity to build a more contextually-correct error message precisely in that line that gives a more contextually-correct error message, if you'd like to submit a PR.

@maxArturo
Copy link
Contributor

Oh a final note - you don't need a custom refine validation! It's as easy as this

  const testSchema = z
    .array(z.number())
    .length(4, { message: "needs to be exactly 4" });

  testSchema.parse([]);

In case that saves you any trouble.

@john-schmitz
Copy link
Contributor Author

fixed with pr #1620

colinhacks pushed a commit that referenced this issue Dec 12, 2022
* Add exact length message for arrays

* Add custom validation message for z.string().length()

* Add exact flag to too_big and too_small

Co-authored-by: Colin McDonnell <colinmcd@alum.mit.edu>
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

Successfully merging a pull request may close this issue.

2 participants