Search code examples
typescriptenumsclass-validator

How to set custom error message IsEnum of class-validator in nestjs


I'm using nestjs and I'm using the @IsEnum(Enum) keyword.

If the values ​​that can be entered into the enum are A, B, C, and if B1 is entered, an error occurs.

response: {
    statusCode: 400,
    message: [ 'each value in tag must be a valid enum value' ],
    error: 'Bad Request'
  },
  status: 400

It simply displays the above log. I want to know what value is wrong.

If I entered A,B1,C, I would like to receive an error message saying 'The value of B1 is incorrect'.

@IsEnum(EnumName, { each: true })
  enumValues: EnumName[] = [];

Solution

  •   import { difference } from 'lodash';
    
      @IsEnum(EnumName, {
        message: (args: ValidationArguments) => {
          const { value, constraints } = args;
          const correctValues = Object.values(constraints[0]);
          const incorrectValues = difference(value, correctValues);
          return `The values of ${incorrectValues} are incorrect`;
        },
        each: true,
      })