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.
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.
Problem Currently,
zod.record()
allows empty objects to pass validation without error.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:
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:
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.