To make Zod error messages dynamic based on the active locale in your Next.js application using `next-i18next`, you can follow these steps:
1. **Passing i18n to your Zod schema**: You can't directly access `i18n` inside your Zod schema definition as it's an external object. One way to handle this is by passing the translated error messages as arguments when defining your schema.
2. **Create a function to generate dynamic Zod schema**: You can create a function that generates your Zod schema dynamically with the translated error messages based on the active locale.
Here's an example of how you can achieve this:
// utils/zodUtils.js
import { z } from 'zod';
export const createMailSchema = (t) => {
return z.object({
email: z
. string({
invalid_type_error: t('zod-errors.invalid_type_error') ?? '',
required_error: t('zod-errors.required_error') ?? '',
})
.email(t('zod-errors.email') ?? ''),
subject: z
.string({
invalid_type_error: t('zod-errors.invalid_type_error') ?? '',
required_error: t('zod-errors.required_error') ?? '',
})
.min(3, t('zod-errors.min') ?? '')
.max(60, t('zod-errors.max') ?? ''),
body: z
.string({
invalid_type_error: t('zod-errors.invalid_type_error') ?? '',
required_error: t('zod-errors.required_error') ?? '',
})
.min(10, t('zod-errors.min') ?? '')
.max(500, t('zod-errors.max') ?? ''),
});
};
Then in your component where you use the Zod schema:
// YourComponent.js
import { useTranslation } from 'next-i18next';
import { createMailSchema } from 'utils/zodUtils';
const YourComponent = () => {
const { t } = useTranslation();
const mailSchema = createMailSchema(t);
// You can now use mailSchema for validation
};
This way, you can ensure that your Zod error messages are dynamically translated based on the active locale in your Next.js application.