简体   繁体   中英

class-transformer @Type() decorator doesn't work

I have a dto file:

export class UpdateUserDto {
  @IsUUID()
  public readonly uuid: string;

  @IsObject()
  @Type(() => UserModelDto)
  public readonly dataToUpdate: UserModelDto;
}

The problem is, it seems @Type() decorator doesn't work. My UserModelDto looks like this:

export class UserModelDto {
  @IsUUID()
  @IsOptional()
  public uuid?: string;

  @IsEmail()
  @IsOptional()
  public email?: string;

  @IsString()
  @IsOptional()
  public password?: string;

  @IsJWT()
  @IsOptional()
  public refreshToken?: string;
}

When I send a request to a controller validation doesn't work for dataToUpdate field however for uuid it does. I've tried many ways but result remains the same.

您忘记添加@validateNested装饰器。

You need to enable { transform: true } inside the ValidationPipe options:

app.useGlobalPipes(
  new ValidationPipe({
    transform: true,
  }),
);

reference: https://docs.nestjs.com/techniques/validation#transform-payload-objects

To ensure errors on validation when extra properties are sent in, you need to make use of the forbidNonWhitelisted option in the ValidaitonPipe . If you just want to strip the values you can use transform: true and whitelist: true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM