nodejs class-validator验证对象数组

时间:2018-03-13 10:54:29

标签: node.js class-validator

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

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

如何使用class-validator进行验证,以便名称字段是必需的,每个对象最少2个字符?

由于

1 个答案:

答案 0 :(得分:2)

要验证项目数组,您需要使用public class Student { private static Student instance = null; private static readonly object locker = new object(); public static Student Instance { get { lock (locker) { if (instance == null) { instance = new Student(); } return instance; } } } public void SomeMethod() { } }

一个完整的例子:

@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); 的验证错误。