Blog>
Snippets

Custom Error Messages and Localization with TanStack Form and Zod

Explain how to customize error messages in Zod validation schemas and localize them for different languages when used with TanStack Form.
import { useForm } from '@tanstack/react-form';
import { zodValidator } from '@tanstack/zod-form-adapter';
import { z } from 'zod';
import i18n from 'i18next';

// Define Zod schema with custom messages
const myFormSchema = z.object({
  name: z.string().min(2, { message: () => i18n.t('errors.shortName') }),
  age: z.number().min(18, { message: () => i18n.t('errors.ageLimit') })
});

// Initialize form with Zod schema validation
const { Form } = useForm({
  validate: zodValidator(myFormSchema)
});
This code initializes a form using TanStack Form with Zod for schema validation. The validation schema defines rules for the fields 'name' and 'age', with custom error messages that are localized using the i18next library. The error messages for validation are functions that return the translated string, allowing for dynamic localization.
// Example of initializing i18next with translations
i18n.init({
  lng: 'en', // Set the language
  resources: {
    en: {
      translation: {
        errors: {
          shortName: 'Name must be at least 2 characters.',
          ageLimit: 'You must be at least 18 years old.'
        }
      }
    },
    fr: {
      translation: {
        errors: {
          shortName: 'Le nom doit comporter au moins 2 caractères.',
          ageLimit: 'Vous devez avoir au moins 18 ans.'
        }
      }
    }
  }
});
This code sets up the i18next library for localization, defining translations for error messages in English and French. It configures the library with a language setting ('lng') and adds resources for each supported language, including custom messages defined for form field validation errors.