halcantara
halcantara

Reputation: 51

Include name inside error class-validator nest

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

Answers (3)

boy SuperBawdy
boy SuperBawdy

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

Daniel Davies
Daniel Davies

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

Alex Choi
Alex Choi

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

Related Questions