Code duplication in refinements #346
eventualbuddha
started this conversation in
Ideas
Replies: 1 comment 1 reply
-
|
You can do this! It's called const People = z.array(Person).superRefine((people, ctx) => {
const duplicateIds = [...findDuplicateIds(people)];
if (duplicateIds.length) {
ctx.addIssue({
code: ZodIssueCode.custom,
message: `person IDs must be unique, but found duplicates: ${duplicateIds.join(
", "
)}`,
});
}
});Instead of returning |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I've been using zod for parsing JSON objects in my project, and I'm trying to replace some custom validation with a zod refinement. However, I've found I'm unable to provide the error messages I want in zod v1. I noticed that v3 added the ability to customize the error message by passing a function instead of a static message. That's good! However, in my case having the "check" and "message" be two different things would mean duplicating the validation. Here's what I'm doing now, for reference.
Here's a simple example below. Note that I have to call
findDuplicateIdsmultiple times:Ideally I'd be able to combine the two, returning errors if there are any and returning nothing if it's valid:
Beta Was this translation helpful? Give feedback.
All reactions