typescriptenumszod

Zod error handling with custom error messages on enums


I want to validate a gender field with Zod using z.nativeEnum(), But my custom error messages don't apply:

gender: z.nativeEnum(Gender, {
        invalid_type_error: 'Le sexe doit être homme ou femme.',
        required_error: 'Le sexe est obligatoire',
      }),

but when not selecting an option the displayed error is:

enter image description here

What's the error here ?


Solution

  • I had to do it that way, by specifying errorMap as function returning an object holding a message field for each issue like below:

      gender: z.nativeEnum(Gender, {
            errorMap: (issue, _ctx) => {
              switch (issue.code) {
                case 'invalid_type':
                  return { message: 'Le sexe doit être homme ou femme.' };
                case 'invalid_enum_value':
                  return { message: 'Le sexe doit être homme ou femme.' };
                default:
                  return { message: 'Sexe est invalide' };
              }
            },
          }),