Nest.js 如果只有定义的字符串,则验证字符串数组
Nest.js validate array of strings if there are defined strings only
在控制器级别的 nest.js 应用程序中,我必须验证 DTO。
我在检查项目是否不为空时遇到了困难(如果任何列表项是 null
或 undefined
,请求应该被拒绝)
下面的代码演示了我配置的验证。
import { ArrayMinSize, IsArray } from 'class-validator'
export class ReminderPayload {
// ...
@IsArray()
@ArrayMinSize(1)
recipients: string[]
}
问题
- 我正在寻求帮助来拒绝使用 body 数据(例如
)的请求
{
"recipients": [
null
]
}
- 如何验证数组项是否只有
string
(如果object在数组项位置应该拒绝处理)?
P.S.
'class-validator'
注入成功,它为我的 API.
产生了一些验证结果
您需要告诉 class-validator 运行 对数组的 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[];
}
Link 到文档。
在控制器级别的 nest.js 应用程序中,我必须验证 DTO。
我在检查项目是否不为空时遇到了困难(如果任何列表项是 null
或 undefined
,请求应该被拒绝)
下面的代码演示了我配置的验证。
import { ArrayMinSize, IsArray } from 'class-validator'
export class ReminderPayload {
// ...
@IsArray()
@ArrayMinSize(1)
recipients: string[]
}
问题
- 我正在寻求帮助来拒绝使用 body 数据(例如 )的请求
{
"recipients": [
null
]
}
- 如何验证数组项是否只有
string
(如果object在数组项位置应该拒绝处理)?
P.S.
'class-validator'
注入成功,它为我的 API.
您需要告诉 class-validator 运行 对数组的 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[];
}
Link 到文档。