类验证器 - 验证对象数组 [英] Class-validator - validate array of objects
问题描述
我在 NestJS 中使用 class-validator 包,我希望验证一组对象,这些对象需要正好有 2 个具有相同布局的对象:
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.
这篇关于类验证器 - 验证对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!