如何在 nest.js 中通过条件验证具有不同 DTO 类型的单个字段名称

问题描述 投票:0回答:1

我在一个DTO中有一个相同的字段名,但是那个字段根据条件有不同的DTO类型。文字有点难懂,看代码就明白了

export class EmailTypeDto {
  @IsEnum(EmailType)
  public type: EmailType;

  @ValidateIf((o) => o.type === EmailType.ACCOUNT_SUCCESS)
  @Type(() => AccountSuccessDto)
  @ValidateNested()
  postData: AccountSuccessDto;

  @ValidateIf((o) => o.type === EmailType.MAIN_INQUIRY)
  @Type(() => MainInquiryDto)
  @ValidateNested()
  postData: MainInquiryDto;
}

我收到无法复制 postData 的错误。 postData 字段名称始终相同,但 postData 的值根据电子邮件类型不同,这些不同的字段在每个电子邮件类型 dto 中确定。

这是我试过的代码,显然不行。 我尝试了@ValidatorConstraint,但找不到方法。 看起来有点像,但不是。

@ValidatorConstraint({ name: 'EmailTypeValidation', async: true })
export class EmailTypeValidation implements ValidatorConstraintInterface {
  async validate(postData: object, args: ValidationArguments) {
    switch (JSON.parse(JSON.stringify(args.object)).type) {
      case EmailType.TEST:
        postData = AccountSuccessDto;
        return true;
      case EmailType.MAIN_INQUIRY:
        postData = MainInquiryDto;
        return true;
    }
  }
}

我尝试为@Type 和@ValidateIf 添加或更改参数,但也没有。

typescript validation nestjs dto
1个回答
0
投票

根据您收到的错误 -

EmailTypeDto
类不能包含 2 个同名的属性。

因此,您应该为

postData
属性使用联合类型,并与
@Validate
装饰器一起用于您的自定义验证类:

import { IsEnum, IsNotEmpty, Validate} from "class-validator";


export class EmailTypeDto {
  @IsEnum(EmailType)
  public type: EmailType;

  @Validate(EmailTypeValidation)
  @IsNotEmpty()
  postData: AccountSuccessDto | MainInquiryDto;

在您的自定义验证类中

EmailTypeValidation
您应该只检查类型是否是所需类型之一:

@ValidatorConstraint({ name: 'EmailTypeValidation', async: true })
export class EmailTypeValidation implements ValidatorConstraintInterface {
  async validate(postData: object, args: ValidationArguments) {
    switch (args.object['type']) {
      case EmailType.ACCOUNT_SUCCESS:
      case EmailType.MAIN_INQUIRY:
        return true;
      default:
        return false;
    }
  }
}

© www.soinside.com 2019 - 2024. All rights reserved.