问题描述
我正在将class-validator包与NestJS一起使用,并且正在寻找一个对象数组,这些对象需要具有两个具有相同布局的对象:
I am using class-validator package with NestJS and I am looking to validate an array of objects that need to have exactly 2 objects with the same layout:
到目前为止,我有:
import { IsString, IsNumber } from 'class-validator';
export class AuthParam {
@IsNumber()
id: number;
@IsString()
type: string;
@IsString()
value: string;
}
和
import { IsArray, ValidateNested } from 'class-validator';
import { AuthParam } from './authParam.model';
export class SignIn {
@IsArray()
@ValidateNested({ each: true })
authParameters: AuthParam[];
}
每个@kamilg响应(我可以强制执行2个元素):
per @kamilg response (I am able to enforce exacly 2 elements):
import { IsArray, ValidateNested, ArrayMinSize, ArrayMaxSize } from 'class-validator';
import { AuthParam } from './authParam.model';
export class SignInModel {
@IsArray()
@ValidateNested({ each: true })
@ArrayMinSize(2)
@ArrayMaxSize(2)
authParameters: AuthParam[];
}
我仍然可以传递一个空数组或带有其他与AuthParam不相关的其他对象的数组.
I still can pass an empty array or an array with some other objects not related to AuthParam.
我应该如何修改它以获得验证?
How I should modify it get validation?
我又如何在数组中强制使用2个必需元素? MinLength(2)似乎与字符串有关...(已解决)
Also how I can enforce mandatory 2 elements in the array? MinLength(2) seems to be regarding string... (resolved)
推荐答案
将@Type(() => AuthParam)
添加到您的数组中,它应该可以工作.嵌套对象(数组)需要Type
装饰器.您的代码变为
Add @Type(() => AuthParam)
to your array and it should be working. Type
decorator is required for nested objects(arrays). Your code becomes
import { IsArray, ValidateNested, ArrayMinSize, ArrayMaxSize } from 'class-validator';
import { AuthParam } from './authParam.model';
import { Type } from 'class-transformer';
export class SignInModel {
@IsArray()
@ValidateNested({ each: true })
@ArrayMinSize(2)
@ArrayMaxSize(2)
@Type(() => AuthParam)
authParameters: AuthParam[];
}
如果使用任何异常过滤器来修改错误响应,请小心.确保您了解类验证器错误的结构.
Be careful if you are using any exception filter to modify the error reponse. Make sure you understand the structure of the class-validator errors.
这篇关于类验证器-验证对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!