在nestjs中,为了验证startDate和endDate的查询参数
1、sartDate必须在endDate之前,这里是自定义验证器
@ValidatorConstraint({ name: 'isBefore', async: false })
export class IsBeforeConstraint implements ValidatorConstraintInterface {
validate(propertyValue: string, args: ValidationArguments) {
console.log('check is before ');
if (args.object[args.constraints[0]]) {
return moment(propertyValue) < moment(args.object[args.constraints[0]]);
} else {
return true;
}
}
defaultMessage(args: ValidationArguments) {
return `"${args.property}" must be before "${args.constraints[0]}"`;
}
}
2、startDate和endDate必须以'YYYY-MM-DD'格式传入
@ValidatorConstraint({ name: 'isRightDateFormat', async: false })
export class DateFormatConstraint implements ValidatorConstraintInterface {
validate(propertyValue: string) {
console.log('check format ' + propertyValue);
return moment(propertyValue, 'YYYY-MM-DD', true).isValid();
}
defaultMessage(args: ValidationArguments) {
return `"${args.property}" must be with format YYYY-MM-DD`;
}
}
所以对于 startDate,我想首先验证格式,然后验证 isBefoer 而不是 endDate,我无法控制验证顺序作为我的以下代码:
export class HistoricalQueryDTO {
@IsNotEmpty()
@ApiProperty()
@Validate(DateFormatConstraint)
@Validate(IsBeforeConstraint, ['endDate'])
startDate: string;
@IsNotEmpty()
@ApiProperty()
endDate: string;
}
另外,如何通过 Annotation 将 costome 验证器应用于 swagger 定义?仅将必需的验证添加到 swagger