我正在尝试使用类验证器和 NestJS 来验证嵌套对象。我已经尝试通过使用 class-transform 中的 @Type
装饰器来关注此 线程,但没有任何运气。这就是我所拥有的:
数据传输协议:
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 验证管道,这是我的引导程序:
async function bootstrap() {
const app = await NestFactory.create(ServerModule);
app.useGlobalPipes(new ValidationPipe());
await app.listen(config.PORT);
}
bootstrap();
它对其他属性工作正常,对象数组是唯一不工作的。
原文由 Leonardo Emilio Dominguez 发布,翻译遵循 CC BY-SA 4.0 许可协议
您期望
positions: [1]
抛出 400 但它被接受了。根据这个 Github 问题,这似乎是类验证器中的一个错误。 If you pass in a primitive type (
boolean
,string
,number
,…) or anarray
instead of an object,它会接受有效的输入,尽管它不应该。除了创建 自定义验证装饰器 之外,我没有看到任何标准的解决方法:
然后在你的 dto 类中使用它: