Home > database >  Zod error handling with custom error messages on enums
Zod error handling with custom error messages on enums

Time:09-01

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 ?

CodePudding user response:

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

CodePudding user response:

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' };
          }
        },
      }),
  • Related