3r-xidongdong-nestjs/src/modules/core/constraints/match.constraint.ts
xidongdong-153 c151657116 feat:自定义数据验证约束
1.学习数据自定义约束
2.给自定义数据约束实现依赖注入
2023-12-12 16:40:19 +08:00

42 lines
1.3 KiB
TypeScript

import {
ValidationArguments,
ValidationOptions,
ValidatorConstraint,
ValidatorConstraintInterface,
registerDecorator,
} from 'class-validator';
/**
* 判断两个字段的值是否相等的验证规则
*/
@ValidatorConstraint({ name: 'isMatch' })
export class MatchConstraint implements ValidatorConstraintInterface {
validate(value: any, args?: ValidationArguments) {
const [relatedProperty] = args.constraints;
const relatedValue = (args.object as any)[relatedProperty];
return value === relatedValue;
}
defaultMessage(args?: ValidationArguments) {
const [relatedProperty] = args.constraints;
return `${relatedProperty} and ${args.property} don't match`;
}
}
/**
* 判断DTO中两个属性的值是否相等的验证规则
* @param relatedProperty 用于对比的属性名称
* @param validationOptions class-validator库的选项
*/
export function IsMatch(relatedProperty: string, validationOptions?: ValidationOptions) {
return (object: RecordAny, propertyName: string) => {
registerDecorator({
target: object.constructor,
propertyName,
options: validationOptions,
constraints: [relatedProperty],
validator: MatchConstraint,
});
};
}