Next.js Discord

Discord Forum

next-intl + zod

Unanswered
Cape horse mackerel posted this in #help-forum
Open in Discord
Cape horse mackerelOP
Hi guys.
Anyone know how to configure the zod error messages when you have internationalization within your app?
So, I want my zod errors/custom messages be taken from translation files depending which locale app is using.
Thanks in advance

3 Replies

Golden-winged Warbler
I was thinking of using something like this: https://github.com/aiji42/zod-i18n

but want something that also works with a i18n solution in the broader context of the full site
Cape horse mackerelOP
Yeah, I've run into that lib but wanted to see other approaches
Cape horse mackerelOP
// hooks/use-my-form.ts
export default function useMyForm() {
  const t = useTranslations(); // from 'next-intl'
  const mySchema = z.object({
    myField: z.string().nonempty(t('common.required_field'))
  });

  return {
    mySchema,
    mySchemaResolver: zodResolver(mySchema)
  }
}

// MyComponent.tsx
const {mySchema,mySchemaResolver} = useMyForm();
type MySchemaType = z.infer<typeof mySchema>;

const {register, formState: {errors}} = useForm<MySchemaType>({
  resolver: mySchemaResolver
});
// the rest of the code

This is also possible but don't know if there are any cons