colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
33.09k stars 1.15k forks source link

Add nonempty() method to zod.record() for empty object validation #3741

Open e-vasiltsov opened 2 weeks ago

e-vasiltsov commented 2 weeks ago

Problem Currently, zod.record() allows empty objects to pass validation without error.

const User = z.object({ name: z.string() });
const UserStore = z.record(z.string(), User);
UserStore.parse({}); // passes

In certain use cases, this behavior is not desired, as an empty object can represent invalid data. For example, when an object is expected to have at least one key-value pair, an empty object should trigger a validation error.

Proposed Solution Introduce a nonempty() method to zod.record() that ensures the record is not empty. This would allow developers to enforce that objects must contain at least one key-value pair. Example usage:

zod.record(z.string(), User).nonempty();
UserStore.parse({}); // throws: "Record cannot be empty"

In this case, an empty object would throw a validation error, while non-empty objects would pass validation as usual.

It would be great to add a custom error message:

// optional custom error message
zod.record(z.string(), User).nonempty({
  message: "Can't be empty!",
});

Next Steps I would like feedback from the maintainers and community to see if this feature would be a valuable addition to Zod. If there’s support for the idea, I’m happy to start working on this feature and submit a pull request.