You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Nestjs中如何验证DTO的属性为非空数字?

问题原因与解决办法

1. 首要排查:验证管道是否启用

class-validator的装饰器需要配合NestJS的ValidationPipe才能生效,大部分不生效的场景都是未正确绑定验证管道。
全局启用管道的代码如下:

// main.ts
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe({
    transform: true, // 开启自动类型转换,配合后续类型校验
    whitelist: true, // 可选,自动过滤DTO未定义的多余属性
  }));
  await app.listen(3000);
}
bootstrap();

注意不要在管道配置中添加skipMissingProperties: true,该配置会跳过对未传字段的校验,直接导致@IsNotEmpty失效

2. 调整装饰器执行顺序

class-validator的装饰器执行顺序为从下到上,你当前的写法会先执行@IsNumber()再执行@IsNotEmpty(),空值场景下@IsNumber()会先抛出错误。如果希望优先校验非空规则,调整装饰器顺序即可:

export class CreateOrderShippingDto implements CreateOrderShippingDtoInterface {
  @ApiProperty({
    type: Number,
  })
  @IsNumber()
  @IsNotEmpty() // 放在下方会优先执行
  readonly orderId: number;
}

3. 依赖检查

确保项目已经安装了校验所需的基础依赖:

npm install class-validator class-transformer

4. 额外补充:兼容字符串格式数字

如果前端传入的是字符串格式的数字(比如"123"),可以添加@Type()装饰器做自动类型转换,避免校验失败:

import { Type } from 'class-transformer';

export class CreateOrderShippingDto implements CreateOrderShippingDtoInterface {
  @ApiProperty({
    type: Number,
  })
  @Type(() => Number)
  @IsNumber()
  @IsNotEmpty()
  readonly orderId: number;
}

内容的提问来源于stack exchange,提问作者Vitor Morais

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 06:15:03