I want to return a custom message on a Zod tuple. I did not find any way to do that.
Returned message: Array must contain at least 4 element(s)
Code:
z.tuple([
z.enum(),
z.number(),
z.string(),
z.array(),
],
{ message: "Needs to be an array." })
//.refine, .min, .length will not work here
What I tried
You can customize the error message using the errorMap
property in params. Read docs here.
Here is how you would do it for your code:
z.tuple([
z.enum(),
z.number(),
z.string(),
z.array(),
], {
errorMap: (issue, ctx) => {
// for too_small
if (issue.code === z.ZodIssueCode.too_small) {
return { message: "Missing values in tuple" };
}
// default message for other errors
return { message: ctx.defaultError };
}
})