nodejs class-validator 验证对象数组

nodejs class-validator validating array of objects

我有一组看起来像这样的对象

[{
  name: 'some name'
  catId: 2,
}, {
  name: 'another name'
  catId: 3,
}]

我如何使用 class-validator 进行验证,以便名称字段是必需的,并且每个对象中的长度至少为 2 个字符?

谢谢

要验证项目数组,您需要使用 @ValidateNested({ each: true })

一个完整的例子:

import { validate, IsString, MinLength, ValidateNested } from 'class-validator';

class MySubClass {
  @IsString()
  @MinLength(2)
  public name: string;

  constructor(name: string ){
    this.name = name;
  }
}

class WrapperClass {
  @ValidateNested({ each: true })
  public list: MySubClass[];

  constructor(list: MySubClass[]) {
    this.list = list;
  }
}

const subClasses = Array(4)
    .fill(null)
    .map(x => new MySubClass('Test'))

subClasses[2].name = null;

const wrapperClass = new WrapperClass(subClasses);
const validationErrors = await validate(wrapperClass);

这将按预期记录 subClasses[2] 的验证错误。