I want to create a nestjs app and want to have the ability to customize the messages of class-validator, so I created a function to get keys I provide to messages and then returns the customized message, the problem is I want to get min value I provide to @Min decorator in DTOs; but it does not exist in error object I get in exceptionFactory.
this Is the DTO:
class GetUsersDto {
@ApiProperty({ required: false })
@IsOptional()
@Min(1, { message: 'validation.min' })
@IsInt()
@Transform((param) => parseInt(param.value, 10))
page?: number;
}
app.useGlobalPipes(
new ValidationPipe({
stopAtFirstError: true,
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
exceptionFactory: (errors) => {
console.log(errors);
const result = errors
.map((error) => {
const key = Object.values(error.constraints)[0];
const message = getMessage(key, error);
return message ? message : getMessage('validation.400');
})
.join('');
return new BadRequestException(result);
},
}),
);
When I log errors inside exceptionFactory I get something like this:
[
ValidationError {
target: GetUsersDto { page: -1 },
value: -1,
property: 'page',
children: [],
constraints: { min: 'validation.min' }
}
]
what I need is to get the minimum value I provided to @Min (which is 1 here), but I get validation.min. How can I get the value provided to @Min?.
we can use context, but providing the same value in two places is error prone and adding context is making decorators a little bit messy.
You can use a global const for that value. like this:
and then you will be able to use that const wherever you want. Yo can even use a separated constans.js file and store all the config values there and import them wherever you need.