Zod + React-hook-form + lingui #2140
-
Wondering if anyone has come across the following issue: I would like to display a translated error message to the user and not sure what is the best approach. const myFormSchema = z.object({
name: z.string().min(3)
})
function MyForm(){
const formMethods = useForm({ resolver: zodResolver(myFormSchema) })
...
} The error I would get from react-hook-form here is the following: So I end up doing this: function MyForm(){
const t = useTrans()
const myFormSchema = z.object({
name: z.string().min(3, t("form_errors.min_length", { label: t(`name`), min: 3 }))
})
const formMethods = useForm({ resolver: zodResolver(myFormSchema) })
...
} Which I feel, defeats the purpose of Any advice? Is there something I'm doing wrong? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
This seems like it's a very complex problem with a few different libraries. I'm happy to help with the zod part. However, I can't really tell where zod is causing a problem. Can you send a reproducible code example of where the problem is with zod? |
Beta Was this translation helpful? Give feedback.
-
Sure, will do so this evening. |
Beta Was this translation helpful? Give feedback.
-
Hi @asafs94 You can use z.setErrorMap in a separate file. https://zod.dev/ERROR_HANDLING?id=customizing-errors-with-zoderrormap import { plural, t } from '@lingui/macro';
import { z } from 'zod';
const customErrorMap: z.ZodErrorMap = (issue, ctx) => {
// console.log(issue, ctx);
switch (issue.code) {
case z.ZodIssueCode.too_small:
const min = (issue.minimum ?? 0) as number;
return {
message: plural(min, {
one: 'Field is required',
other: `Field must contain at least # characters`,
}),
};
}
return { message: ctx.defaultError };
};
z.setErrorMap(customErrorMap); |
Beta Was this translation helpful? Give feedback.
This seems like it's a very complex problem with a few different libraries. I'm happy to help with the zod part. However, I can't really tell where zod is causing a problem. Can you send a reproducible code example of where the problem is with zod?