Validating size and extensions

Basic rules for file validation.

We should begin by asking: which rules do we want the file to follow? Usually it's a nice idea to enforce a maximum size and allowed extensions. We may then have the following requirements:

  • Max size - 2MB

  • Allowed extensions - PNG/JPEG

Very well! To apply these rules, we must do the following: in the parameters of @UploadedFile(), let's instantiate a ParseFilePipe. Its constructor has as parameter an options object. One of them is a FileValidator array. Fortunately, Nest offers standard validators, which are exactly what we want: MaxFileSizeValidator and FileTypeValidator. We should then instantiate them, passing their respective rules as arguments. We then get the following result:

new ParseFilePipe({
  validators: [
    new MaxFileSizeValidator({ maxSize: 2 * 1024 * 1024 }),
    new FileTypeValidator({ fileType: /png|jpeg/ }),
  ],
}),

Well, we got validation working... but this solution is still quite crude, don't you think? We can notice the following flaws:

  • The max size is defined in bytes

  • To define many extensions, a regex is needed

  • We may want to define a type for allowed extensions, as to have better type safety

  • If it's common to validate files using these two rules, it would be convenient to have a factory function to instantiate both these validators

From now on, we'll start to create an entire structure to aid us when managing files.

Commit - Validating incoming files

Last updated