React-hook-form next-I18next ZodResolver Typescript #9452
Replies: 3 comments
-
Love it, thanks very much for sharing! we need more of those. |
Beta Was this translation helpful? Give feedback.
-
thanks a lot |
Beta Was this translation helpful? Give feedback.
-
Hi @tonyjara, Thanks for the great work on this! "i18next": "^24.2.2",
"react-i18next": "^15.4.1",
"zod": "^3.24.2",
"@hookform/resolvers": "^4.1.3",
"react-hook-form": "^7.54.2" However, I wasn't able to get it working correctly. Here's a simplified version of my schema and how I'm using Schema definition: const createLoginSchema = (t: TFunction) =>
z.object({
username: z
.string({
required_error: t("login:username.validation.required"),
})
.min(1, {
message: t("login:username.validation.required"),
}),
password: z
.string({
required_error: t("login:password.validation.required"),
})
.min(1, {
message: t("login:password.validation.required"),
}),
}); Form setup: function Login() {
const { t } = useTranslate(["login"]);
type LoginFormValues = z.infer<ReturnType<typeof createLoginSchema>>;
const { register, handleSubmit, formState } = useForm<LoginFormValues>({
resolver: zodResolver(createLoginSchema(t)),
defaultValues: {
username: "",
password: "",
},
mode: "onChange",
});
} Just wondering—does this approach still work with the latest versions listed above? Or is there an updated pattern recommended for using i18n with Zod and react-hook-form? Thanks in advance! |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi, so I've been struggling with validation and i18next . I like having my form validations on a separate file, and for some reason the 't' from the useTranslation hook does not expose a generic type that I can easily pass down on a validation function. So anyways, this is how I solved that problem.
When using I18next with typescript we have to create a file with our imported namespaces.
Since we know that 't' takes strings concatenated strings with a semicolon, we can create a type with generics that takes the I18nNamespaces.
Now we can pass the 't' to our resolver function:
And now our validation file can has support for the 't' strings:
That's it, you can also use this new type to use 't' as a parameter anywhere else you like. Leaving this here in hopes it helps someone.
Beta Was this translation helpful? Give feedback.
All reactions