class-transformer and class validator: Show @exposed name in class-validator error
Asked Answered
E

1

8

I have a NestJS project in which I'm using both class validator and class transformer, and I need the class-transformer to execute before the class-validator throws an error.

Given the following class:

export class CreateProfileDto {
  @IsString()
  @Expose({ name: 'name' })
  profileName!: string;

  @IsBoolean()
  @Expose({ name: 'active'})
  profileActive!: boolean;
}

I need to expose the errors with the property name and not the property profileName and the same goes for the other property.

Any straight forward idea to manage this? Can't ask the frontend to send me the properties with different names, that's why I need to adjust to them.

I thought to do so through a pipe but can't manage to use it before the error explodes.

Current error format:

{
    "statusCode": 400,
    "error": "Bad Request",
    "message": [
        {
            "target": {
                "profileName": 1
            },
            "value": 1,
            "property": "profileName",
            "children": [],
            "constraints": {
                "isString": "profileName must be a string"
            }
        }
    ]
}

Desired error format:

{
    "statusCode": 400,
    "error": "Bad Request",
    "message": [
        {
            "target": {
                "name": 1
            },
            "value": 1,
            "property": "name",
            "children": [],
            "constraints": {
                "isString": "name must be a string"
            }
        }
    ]
}
Eatables answered 12/12, 2019 at 17:22 Comment(2)
You could pass the property name by context to decorator. Look here: npmjs.com/package/class-validator#passing-context-to-decoratorsSpawn
I have this very same issue, expose is not returning the exposed name but the original one.Subspecies
M
0

It implies some extra work but you can personalize the error message by passing a ValidationOptions object to the decorator

export class CreateProfileDto {
  @IsString({ message: 'name must be a string' })
  @Expose({ name: 'name' })
  profileName!: string;
}

Passing a function is also an option:

export class CreateProfileDto {
  @IsString({ message: () => 'name must be a string' })
  @Expose({ name: 'name' })
  profileName!: string;
}
Mooncalf answered 31/1 at 21:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.