Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating custom validator for image uploading at Nest.js with class-validator package

I want to validate the mimetype of file at Nest.js. But i can't.

@UseInterceptors(FileInterceptor('image'))
  @Post('upload_profile_photo')
  async uploadProfilePhoto(@UploadedFile() image: UploadImageDto) {
    return image;
}

UploadImageDto.ts

import { IsImageFile } from '../validators/IsImageFile';

export class UploadImageDto {
  @Validate(IsImageFile)
  mimetype: string;
}

IsImageFile.ts

@ValidatorConstraint({ async: false, name: 'image' })
export class IsImageFile implements ValidatorConstraintInterface {
  validate(mimeType: string, args: ValidationArguments) {
    // nothing is written on the console
    console.log(mimeType);

    const acceptMimeTypes = ['image/png', 'image/jpeg'];

    const fileType = acceptMimeTypes.find((type) => type === mimeType);

    if (!fileType) return false;

    return true;
  }

  defaultMessage(validationArguments?: ValidationArguments): string {
    return 'The file type was not accepted.';
  }
}

My custom decorator doesn't execute. Anyone help me?


1 Answers

You can define a function which does the validation, and use it in annotation above the property you wish to validate, like so :

import { ValidationOptions, registerDecorator } from 'class-validator';

export function IsImageFile(options?: ValidationOptions) {
  return (object, propertyName: string) => {
    registerDecorator({
      target: object.constructor,
      propertyName,
      options,
      validator: {
        validate(mimeType) {
          const acceptMimeTypes = ['image/png', 'image/jpeg'];
          const fileType = acceptMimeTypes.find((type) => type === mimeType);
          return !fileType;
        },
      },
    });
  };
}
export class UploadImageDto {
  @IsImageFile({message: invalid mime type received})
  mimetype: string;
}
like image 135
Dus Avatar answered Oct 26 '25 05:10

Dus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!