class-validator icon indicating copy to clipboard operation
class-validator copied to clipboard

question: ValidateNested custom messages cannot be fully overwritten

Open ArcherGu opened this issue 4 years ago • 2 comments

I was trying to... I want to use custom messages when I use ValidateNested. But it always comes with a prefix

The problem: example:

class Cat {
  @IsNotEmpty({ message: "cat's name cant be empty" })
  name: string
  // ...
}


class User {
  @ValidateNested()
  @Type(() => Cat)
  pet: Cat
  //...
}

verify:

// user
{
  pat: {}
}

// expect
"cat's name cant be empty"

// actually
"pat.cat's name cant be empty"   // <- pat prefix here

ArcherGu avatar Nov 30 '21 01:11 ArcherGu

I'm also facing the same issue. Is there a way to prevent the library from composing the error message when using @ValidateNested or when we are validating and array?

GeorgianStan avatar Jan 29 '22 16:01 GeorgianStan

The only way to avoid this is seeing from another perspective: just catch from exceptionFactory in main.ts. You could return one or all errors.

app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      transform: true,
      exceptionFactory: (errors) => {
        const error = !!errors[0].children.length
          ? errors[0].children[0].constraints
          : errors[0].constraints;

        return new BadRequestException(Object.values(error)[0]);
      },
    }),
  );
  

cesargillao avatar May 06 '23 22:05 cesargillao