2

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

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

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

谢谢

4

1 回答 1

6

要验证一组项目,您需要使用@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]这将按预期记录验证错误。

于 2018-03-17T19:16:06.237 回答