如何使用 Nest.js 中的类验证器验证数组中每个对象的字段

Iho*_*hor 2 javascript validation node.js class-validator nestjs

import { ArrayMaxSize, ArrayMinSize, IsArray, IsBoolean, IsString, ValidateNested } from "class-validator";
import { Transform, Type } from "class-transformer";

class CreateAnswerDto {
  @IsBoolean()
  readonly isTrue: string;

  @IsString()
  title: string;

  @IsString()
  description: string;
}

const transformAnswers = answers => {
  return JSON.parse(answers.value);
};

export class CreateQuestionDto {
  @Transform(transformAnswers, { toClassOnly: true })
  @IsArray()
  @ArrayMinSize(4)
  @ArrayMaxSize(4)
  @ValidateNested({ each: true })
  @Type(() => CreateAnswerDto)
  readonly answers: CreateAnswerDto[];

  @IsString()
  readonly title: string;
}
Run Code Online (Sandbox Code Playgroud)

所以我有相同的代码,并且我想验证答案中的每个对象字段,但此代码不起作用。如果我发送了错误的数据,则此验证会跳过它。我怎样才能正确验证我的答案?

谢谢你的帮助!

Iho*_*hor 5

所以,我解决了这个问题。

import {
  ArrayMaxSize,
  ArrayMinSize,
  IsArray,
  IsNotEmpty,
  IsString,
  IsUUID,
  MinLength,
  ValidateNested,
} from "class-validator";
import { plainToClass, Transform, Type } from "class-transformer";
import { CreateAnswerDto } from "src/modules/answers/dto/create-answer.dto";
import { HasMimeType, IsFile, MaxFileSize, MemoryStoredFile } from "nestjs-form-data";

export class CreateQuestionDto {
  @ValidateNested({ each: true })
  @Transform(({ value }) => plainToClass(CreateAnswerDto, JSON.parse(value)))
  @IsArray()
  @ArrayMinSize(4)
  @ArrayMaxSize(4)
  @Type(() => CreateAnswerDto)
  readonly answers: CreateAnswerDto[];

  @IsUUID()
  @IsNotEmpty()
  readonly category_id: string;

  @IsFile()
  @MaxFileSize(220000)
  @HasMimeType(["image/jpeg", "image/png"])
  readonly image: MemoryStoredFile;

  @IsString()
  @MinLength(5)
  readonly title: string;
}
Run Code Online (Sandbox Code Playgroud)

我的回答是:

import { Exclude } from "class-transformer";
import { IsBoolean, IsNotEmpty, IsString, MinLength } from "class-validator";

export class CreateAnswerDto {
  @IsBoolean()
  @IsNotEmpty()
  readonly isTrue: boolean;

  @IsString()
  @MinLength(5)
  readonly title: string;

  @IsString()
  @MinLength(5)
  readonly description: string;

  @IsString()
  @MinLength(5)
  readonly displayMessage: string;

  @Exclude()
  readonly id: string;

  constructor(partial: Partial<CreateAnswerDto>) {
    Object.assign(this, partial);
  }
}
Run Code Online (Sandbox Code Playgroud)