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

Nest.js使用class-validator校验字符串数组仅含非空有效字符串

解决方案

你需要使用class-validator提供的each参数对数组每一个元素单独应用校验规则,修改后的DTO代码如下:

import { ArrayMinSize, IsArray, IsString, IsNotEmpty } from 'class-validator'

export class ReminderPayload {
    // ...
    @IsArray()
    @ArrayMinSize(1)
    @IsString({ each: true })
    @IsNotEmpty({ each: true })
    recipients: string[]
}

规则说明

  • @IsString({ each: true }):遍历校验数组的每一个元素都必须是字符串类型,非字符串(数字、对象、布尔值等)都会触发校验失败,解决你提出的第二个问题
  • @IsNotEmpty({ each: true }):遍历校验数组的每一个元素都不能为null、undefined、空字符串,解决你提出的第一个问题

如果你仅需要排除null和undefined,允许空字符串存在,可以将@IsNotEmpty({ each: true })替换为@IsDefined({ each: true })

可选配置检查

如果修改规则后校验未生效,可确认项目中全局校验管道是否开启了自动转换:

// main.ts 全局管道配置参考
app.useGlobalPipes(new ValidationPipe({
  transform: true,
  whitelist: true
}))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:06:01