简体   繁体   中英

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[] = [];
  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,
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM