Filter invalid records from array #5174
matthew-gladman-oua
started this conversation in
Ideas
Replies: 1 comment
-
|
There is no filterIfInvalid method or built-in functionality in Zod (v4) that automatically filters out invalid records from an array during parsing as described in your example. Zod’s array schema will fail validation if any element in the array is invalid(1). If you want to filter out invalid array items, you will need to handle this logic outside of Zod by manually filtering the array before parsing, or by parsing each item individually with safeParse and keeping only the valid ones(2). 📚 Sources: Have another question? Just tag @inkeep. |
Beta Was this translation helpful? Give feedback.
0 replies
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.
Uh oh!
There was an error while loading. Please reload this page.
-
A problem we've had came up a few times is a deeply nested child is invalid, causing the entire schema to be invalid. In our particular use case, we would rather just filter out the invalid records rather than fail to parse instead.
So something like:
This allows a bit more flexibility in how parsing works, we still avoid invalid data, but items we don't mind being filtered are removed. It also returns back the data so that a consumer can log or manipulate this data as needed and fix the data long-term. This is especially good on legacy projects where the data quality is known to be poor, and we don't need to loosen up the Zod schema to allow parsing the data, so we can filter it out afterwards.
I don't believe this should be the default behavior and would have to be opted in on a per-array basis.
Beta Was this translation helpful? Give feedback.
All reactions