Handle object schema keys with handlePath
mainWhen validating objects (e.g., z.object), you can include the object key in the error message using the {{path}} placeholder.
To enable this:
- Use a translation key suffixed with
_with_path(e.g.,invalid_type_with_path). - If you want to map technical keys (like
userName) to human-readable labels (likeUser's name), use thehandlePath.keyPrefixoption inmakeZodI18nMapto point to a specific section in your translation files.
i18next.init({
lng: "en",
resources: {
en: {
zod: {
errors: {
invalid_type: "Expected {{expected}}, received {{received}}",
invalid_type_with_path: "{{path}} is expected {{expected}}, received {{received}}",
},
},
form: {
paths: {
userName: "User's name",
},
},
},
},
});
z.setErrorMap(
makeZodI18nMap({
ns: ["zod", "form"],
handlePath: {
keyPrefix: "paths",
},
})
);
const schema = z.object({ userName: z.string() });
schema.parse({ userName: 1 }); // => User's name is expected string, received number