Reputation: 51
I would like to know if it is possible and how can I return the field name along with the validation error message.
Example: "message": { name: "Name is required", username: "Username is required", }
instead of:
"message": [ "Name is required", "Username is required", ]
Upvotes: 5
Views: 1781
Reputation: 1
exceptionFactory: (errors) => {
throw new BadRequestException({
statusCode: 400,
message: 'Validation failed',
errors: errors.map((error) => ({
field: error.property,
errors: Object.values(error.constraints),
})),
});
},
You can use this Code. You can get it { field:string,errorMessage:string }
Upvotes: 0
Reputation: 158
This is answered in NestJs - Class-validator not returning full validation error object
You can add exceptionFactory: (errors) => new BadRequestException(errors),
When you construct your ValidationPipe to get a detailed error response that includes the field name
Upvotes: 2
Reputation: 185
I'm not sure this is what you want.
const message : {name : string, username : string} = {name :'alex', username : 'halo'}
So if you type to '{name : string, username : string}' typescript will allow only object that have keys name and username.
Upvotes: -2