zod
zod copied to clipboard
add uniq to ZodArray
This PR add a uniq validation to ZodArray to validate that the array doesn't contains any duplicates.
ps: Currently this validation doesn't check for deep duplications but only simple ones.
Deploy Preview for guileless-rolypoly-866f8a ready!
Built without sensitive environment variables
Name | Link |
---|---|
Latest commit | 1ce439b878b3ea37263f767743d3a757f7226716 |
Latest deploy log | https://app.netlify.com/sites/guileless-rolypoly-866f8a/deploys/637b9576af178900084b0eb8 |
Deploy Preview | https://deploy-preview-1386--guileless-rolypoly-866f8a.netlify.app |
Preview on mobile | Toggle QR Code...Use your smartphone camera to open QR code link. |
To edit notification comments on pull requests, go to your Netlify site settings.
By the way in case of unique array
schema may be prefer to use z.set
instead of array?
@ArthurKa, One of the main use of Zod is to validate external data input as JSON message (from http call or Mongo collection for example). Those kind of messages doesn't supports Sets as Sets or in memory objects and aren't par of the JSON specification. To validate arrays with uniq items comming from JSON inputs you can't use z.set()
Make sense. What about .refine
?
const schema = z.number().array().refine(e => new Set(e).size === e.length, {
message: 'Array should have unique elements',
});
Refine would definitely work and that's what I'm using currently. But I think this uniq check is a quite common use case and a great functionality to add to Zod. It would definitely be cleaner to used than using big refine on all arrays that need this checks. By the way quite all checks of Zod (like min, max, length, elements on arrays) could be implemented with refine, but we add then to the library to make it cover more use cases.
We can discuss the implementation but I also agree having a .uniq
shortcut is good :D
Is it possible to add a comparator function? The use case I have in mind is to check a subset of duplicate properties. For example:
const schema = z.string().array().uniq((a, b) => a.id === b.id);
// ✗ Failure
schema.parse([
{ "id": "1", "firstName": "Alice" },
{ "id": "1", "firstName": "Bob" }, // Error: duplicate `id` property
]);
@psirenny, Following your suggestion I added two functions on ZodArray to my PR uniqBy and uniqWith that respectively take a mapping function and a comparator function for custom unicity checks.
Any chance of getting this released?
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.