| 1 | import { |
| 2 | registerDecorator, |
| 3 | ValidationOptions, |
| 4 | ValidatorConstraint, |
| 5 | ValidatorConstraintInterface, |
| 6 | ValidationArguments, |
| 7 | } from 'class-validator'; |
| 8 | import { isValidObjectId } from 'mongoose'; |
| 9 | |
| 10 | @ValidatorConstraint({ name: 'isObjectId', async: false }) |
| 11 | export class IsObjectIdConstraint implements ValidatorConstraintInterface { |
| 12 | validate(value: any) { |
| 13 | if (!value) return true; |
| 14 | return isValidObjectId(value); |
| 15 | } |
| 16 | |
| 17 | defaultMessage(args: ValidationArguments) { |
| 18 | return `${args.property} 必须是有效的 ObjectId`; |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | export function IsObjectId(validationOptions?: ValidationOptions) { |
| 23 | return function (object: object, propertyName: string) { |
| 24 | registerDecorator({ |
| 25 | name: 'isObjectId', |
| 26 | target: object.constructor, |
| 27 | propertyName: propertyName, |
| 28 | options: validationOptions, |
| 29 | validator: IsObjectIdConstraint, |
| 30 | }); |
| 31 | }; |
| 32 | } |
| 33 |