class-validator
class-validator copied to clipboard
question: ValidateNested custom messages cannot be fully overwritten
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
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?
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]);
},
}),
);