Ser*_*gii 24 validation request typescript nestjs
在控制器级别的 Nest.js 应用程序中,我必须验证 DTO。
我很难检查项目是否不为空(如果任何列表项目为null
或,则请求应被拒绝undefined
)
下面的代码演示了我配置的验证。
import { ArrayMinSize, IsArray } from 'class-validator'
export class ReminderPayload {
// ...
@IsArray()
@ArrayMinSize(1)
recipients: string[]
}
Run Code Online (Sandbox Code Playgroud)
{
"recipients": [
null
]
}
Run Code Online (Sandbox Code Playgroud)
string
唯一(如果对象位于数组项位置,则应拒绝处理)?'class-validator'
注入成功,它为我的 API 生成了一些验证结果。
HMi*_*adt 49
each
您需要告诉类验证器对数组的项目运行验证。将您的有效负载 DTO 更改为以下内容:
import { ArrayMinSize, IsArray, IsString } from 'class-validator';
export class ReminderPayloadDto {
// ...
@IsArray()
// "each" tells class-validator to run the validation on each item of the array
@IsString({ each: true })
@ArrayMinSize(1)
recipients: string[];
}
Run Code Online (Sandbox Code Playgroud)
链接到有关此的文档。
归档时间: |
|
查看次数: |
26030 次 |
最近记录: |