使用类验证器和 nestjs 验证嵌套对象 [英] Validate nested objects using class validator and nestjs
问题描述
我正在尝试使用类验证器和 NestJS 来验证嵌套对象.我已经尝试使用 class-transform 中的 @Type
装饰器来关注这个 thread 和没有任何运气.这是我所拥有的:
I'm trying to validate nested objects using class-validator and NestJS. I've already tried following this thread by using the @Type
decorator from class-transform and didn't have any luck. This what I have:
DTO:
class PositionDto {
@IsNumber()
cost: number;
@IsNumber()
quantity: number;
}
export class FreeAgentsCreateEventDto {
@IsNumber()
eventId: number;
@IsEnum(FinderGamesSkillLevel)
skillLevel: FinderGamesSkillLevel;
@ValidateNested({ each: true })
@Type(() => PositionDto)
positions: PositionDto[];
}
我也在使用内置的 nestjs 验证管道,这是我的引导程序:
I'm also using built-in nestjs validation pipe, this is my bootstrap:
async function bootstrap() {
const app = await NestFactory.create(ServerModule);
app.useGlobalPipes(new ValidationPipe());
await app.listen(config.PORT);
}
bootstrap();
它对其他属性工作正常,对象数组是唯一一个不工作的对象.
It's working fine for other properties, the array of objects is the only one not working.
推荐答案
您期望 positions: [1]
抛出 400,但它被接受了.
You are expecting positions: [1]
to throw a 400 but instead it is accepted.
根据这个Github issue,这似乎是类验证器中的错误.如果您传入原始类型(boolean
、string
、number
、...)或 array
对象,它会接受输入为有效,尽管它不应该.
According to this Github issue, this seems to be a bug in class-validator. If you pass in a primitive type (boolean
, string
, number
,...) or an array
instead of an object, it will accept the input as valid although it shouldn't.
除了创建自定义验证装饰器外,我没有看到任何标准的解决方法一个>:
import { registerDecorator, ValidationOptions, ValidationArguments } from 'class-validator';
export function IsNonPrimitiveArray(validationOptions?: ValidationOptions) {
return (object: any, propertyName: string) => {
registerDecorator({
name: 'IsNonPrimitiveArray',
target: object.constructor,
propertyName,
constraints: [],
options: validationOptions,
validator: {
validate(value: any, args: ValidationArguments) {
return Array.isArray(value) && value.reduce((a, b) => a && typeof b === 'object' && !Array.isArray(b), true);
},
},
});
};
}
然后在你的 dto 类中使用它:
and then use it in your dto class:
@ValidateNested({ each: true })
@IsNonPrimitiveArray()
@Type(() => PositionDto)
positions: PositionDto[];
这篇关于使用类验证器和 nestjs 验证嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!