Allow array to return only valid items and not fail whole array #1824
-
When validating an array, I would like to only return the valid items in an array and not fail if one item fails. This is a very basic example const schema = z.object({
arr: z.array(z.number())
})
const result = schema.safeParse({arr: [1,2,"3"]}) I would like this to return only the valid items arr: [1,2] I tried using |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 1 reply
-
Hi @bmeverett, I don't know if Zod maintainers will support this specific claim in the lib, but you can build a custom validator that uses I've implemented something like that just as a proof of concept: const validator = (schema: z.Schema<any, any>) => (data: object) => {
const response = schema.safeParse(data);
if (response.success === false) {
const errorPaths = response.error.issues.map((issue) => issue.path);
let filteredData = data;
errorPaths.forEach(
(error) => (filteredData = filterByPath(filteredData, error))
);
return filteredData;
}
return data;
};
const result = validator(schema)(input); The most difficult part is the I would suggest you develop your own for your needs. For reference, you can see my implementation here in StackBlitz. |
Beta Was this translation helpful? Give feedback.
-
@bmeverett const schema = z.object( {
arr: z.any().array().transform(
arr => arr.map( item =>
z.number().safeParse( item ).success ? item : undefined
).filter( Boolean )
),
} )
console.log( schema.parse( { arr: [ 1, 2, '3' ] } ) ) // { arr: [ 1, 2 ] } |
Beta Was this translation helpful? Give feedback.
-
Thanks @JacobWeisenburger and @lucassarcanjo I think I can work with these. |
Beta Was this translation helpful? Give feedback.
-
Here's what I ended up with, based on @JacobWeisenburger's answer: function filteredArray<T>(schema: z.ZodType<T>) {
return z.any().array().transform((arr) => (
arr.map((item) => schema.safeParse(item).success ? item as T : undefined)
.filter((item): item is T => Boolean(item))
));
} Usage: const noteSchema = z.object({
tag: filteredArray(tagSchema).catch([]),
}); The type of |
Beta Was this translation helpful? Give feedback.
-
This is probably reason for me to leave Zod behind. Proposed solutions drop error messages or require to traverse paths. Basically, there is no way to make parsing more greedy. I wonder why My expectations from
From compatibility point of view it would require to change |
Beta Was this translation helpful? Give feedback.
Hi @bmeverett,
I don't know if Zod maintainers will support this specific claim in the lib, but you can build a custom validator that uses
error.issues
to filter it manually based on invalid properties/items issued by zod.I've implemented something like that just as a proof of concept: