zod
zod copied to clipboard
Access .describe() from superRefine and errors
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}`
});
})
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.
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.
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