Skip to content

Allow array to return only valid items and not fail whole array #1824

Answered by lucassarcanjo
bmeverett asked this question in Q&A
Discussion options

You must be logged in to vote

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:

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 r…

Replies: 5 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Answer selected by JacobWeisenburger
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@AkisArou
Comment options

Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
6 participants
Converted from issue

This discussion was converted from issue #1547 on January 05, 2023 15:38.