4

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 ?

Ismail_Aj
  • 332
  • 1
  • 4
  • 17

2 Answers2

6

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' };
          }
        },
      }),
Ismail_Aj
  • 332
  • 1
  • 4
  • 17
4

You are missing one of the error paths invalid_enum_value. It's because the default option is considered a possible value: 'Sélectionnez un option'. This option isn't one of the zod Gender enums

gender: z.nativeEnum(Gender, {
        invalid_type_error: 'Le sexe doit être homme ou femme.',
        required_error: 'Le sexe est obligatoire',
        invalid_enum_value: 'Please select one of the options'
      }),

enter image description here

Robert Rendell
  • 1,658
  • 15
  • 18