我有一个看起来像这样的对象数组
[{
name: 'some name'
catId: 2,
},
{
name: 'another name'
catId: 3,
}]
如何使用class-validator进行验证,以便名称字段是必需的,每个对象最少2个字符?
由于
答案 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);
的验证错误。