我有一个用于验证的 Dto 类。我有一个全局验证管道,其属性 stopAtFirstError 设置为 true。当我运行代码时,即使第一个装饰器返回错误消息,验证装饰器也会执行。
Nest.js Main.ts 文件
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
stopAtFirstError: true
}),
);
用于验证的 Dto 类。
export class LeaveApplicationBodyDto {
@ValidateIf((o) => regualarLeaves.includes(o.type))
@IsRequired()
@IsUniqueDate()
@ValidateNested({ each: true })
@Type(() => LeaveMetadata)
metadata: LeaveMetadata[];
@IsString()
@IsIn([...regualarLeaves, ...specialLeaves])
type: string;
@ValidateIf((o) => specialLeaves.includes(o.type))
@IsYYYYMMDDFormat()
@IsString()
@IsNotHoliday()
startDate: String;
@IsString()
remark: string;
}
这里
@IsRequired()
和 @IsuniqueDate()
是用于验证目的的自定义装饰器。
如果元数据属性未通过 POST 请求正文发送,则 IsRequired 返回 false。在 IsRequired()
返回 false 后,代码移动到 IsUnique()
,通过 JS 提供的 .map()
方法检查对象的数组。由于缺乏提前终止代码错误而引发 cannot read property of undefined
问题是为什么
StopAtFirstError:true
没有按预期工作,或者我错过了什么。