validationnestjsclass-validator

Customize error message in Nest js using class-validator


I am working on a nest project, and using class-validator for validation.

Currently if there is any validation error, I am getting error response as

{
    "statusCode": 400,
    "message": [
        "Title is too long. Maximal length is 50 characters, but actual is $value",
        "Title is too short. Minimal length is 10 characters, but actual is $value"
    ],
    "error": "Bad Request"
}

But instead of message as array of string, can we have message as array of object. So, that FE can easy figure out which field is having the error, like

{
    "message": [
        { "field": "title", "error": "Title is too long. Maximal length is 50 characters, but actual is $value" },
        { "field": "title", "error": "Title is too short. Minimal length is 10 characters, but actual is $value" }
    ]
}

Solution

  • You can use exception filters in NestJS to handle or add custom user-friendly responses.

    However, for the class-validator, there is the same mechanism by using exceptionFactory() in your validationPipe to modify the error returned by the class-validator, here is an example code for it:

    app.useGlobalPipes(
      new ValidationPipe({
        exceptionFactory: (validationErrors: ValidationError[] = []) => {
          return new BadRequestException(
            validationErrors.map((error) => ({
              field: error.property,
              error: Object.values(error.constraints).join(', '),
            })),
          );
        },
      }),
    );
    

    Hope it will works for you!