zod icon indicating copy to clipboard operation
zod copied to clipboard

Access .describe() from superRefine and errors

Open ElYaiko opened this issue 6 months ago • 2 comments

This seems to be the only way that could work to add labels/metadata to schemas It would be good to access this data from superRefine and errors so they can be referenced in message errors, ex:

zod.string().describe('name').superRefine((value, context) => {
  context.addIssue({
    message: `Invalid ${context.description}`
  });
})

ElYaiko avatar May 18 '25 05:05 ElYaiko

Generally accessing metadata inside the parsing path is an anti-pattern. Keep in mind that metadata data is attached to a specific instance and Zod methods return a new instance. This may result in surprising behavior around metadata (one of the reasons I discourage referencing it in validation)

const A = z.string().meta({ hello: "true" });
A.meta(); // => { hello: "true" }

const B = A.refine(_ => true);
B.meta(); // => undefined

I added a note to the documentation to this effect.

colinhacks avatar May 18 '25 20:05 colinhacks

Generally accessing metadata inside the parsing path is an anti-pattern. Keep in mind that metadata data is attached to a specific instance and Zod methods return a new instance. This may result in surprising behavior around metadata (one of the reasons I discourage referencing it in validation)

const A = z.string().meta({ hello: "true" }); A.meta(); // => { hello: "true" }

const B = A.refine(_ => true); B.meta(); // => undefined I added a note to the documentation to this effect.

I understand, so what another alternatives would you recommend to defining labels to use in the refines and error maps?, for now I only have the idea of using the path property to mapping to any metadata or description from the Schema.

ElYaiko avatar May 21 '25 02:05 ElYaiko

Perhaps something like this:

const A = z.string().describe("name");
const B = A.superRefine((val, ctx) => {
  ctx.addIssue({
    message: `Invalid ${A.description}`,
  });
});

B.parse("test"); // Should pass

colinhacks avatar Jun 11 '25 07:06 colinhacks