| 1 | import { |
| 2 | registerDecorator, |
| 3 | ValidationArguments, |
| 4 | ValidatorConstraint, |
| 5 | ValidatorConstraintInterface, |
| 6 | } from 'class-validator'; |
| 7 | |
| 8 | @ValidatorConstraint({ name: 'isValidImageUrl', async: false }) |
| 9 | class IsValidImageUrlConstraint implements ValidatorConstraintInterface { |
| 10 | validate(value: string) { |
| 11 | if (!value) return false; |
| 12 | |
| 13 | // 检查是否是有效的图片URL |
| 14 | const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']; |
| 15 | return imageExtensions.some((ext) => value.toLowerCase().endsWith(ext)); |
| 16 | } |
| 17 | |
| 18 | defaultMessage(args: ValidationArguments) { |
| 19 | return `${args.property}必须是有效的图片URL地址`; |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | export function IsValidImageUrl() { |
| 24 | return function (object: object, propertyName: string) { |
| 25 | registerDecorator({ |
| 26 | target: object.constructor, |
| 27 | propertyName, |
| 28 | validator: IsValidImageUrlConstraint, |
| 29 | }); |
| 30 | }; |
| 31 | } |
| 32 |