# MaxFileSizeValidator

**Kind:** Class

**Source:** [`packages/common/pipes/file/max-file-size.validator.ts`](https://github.com/nestjs/nest/blob/master/packages/common/pipes/file/max-file-size.validator.ts#L47)

**Part of:** [Common](subsystem-packages-common)

Defines the built-in MaxSize File Validator

`MaxFileSizeValidator` is a built-in file validator that checks whether an uploaded file is smaller than a configured maximum size. It is typically used with NestJS `ParseFilePipe` to reject oversized uploads before they reach application logic.

**Extends:** `FileValidator`

## Methods

| Method | Signature | Returns |
|---|---|---|
| `buildErrorMessage` | `buildErrorMessage(file: IFile)` | `string` |
| `isValid` | `isValid(file: IFile)` | `boolean` |

## Where it refuses work

- `MaxFileSizeValidator` stops the work with an early return when `errorMessage`.
- `MaxFileSizeValidator` stops the work with an early return when `message`.
- `MaxFileSizeValidator` stops the work with an early return when `file?.size`.
- `MaxFileSizeValidator` stops the work with an early return when `!this.validationOptions || !file`.

## Diagram

```mermaid
graph LR
  A[Incoming uploaded file] --> B[ParseFilePipe]
  B --> C[MaxFileSizeValidator]
  C --> D{file.size < maxSize?}
  D -->|Yes| E[Continue request handling]
  D -->|No| F[buildErrorMessage()]
  F --> G[Return validation error]
```

## Usage

```ts
import {
  Controller,
  MaxFileSizeValidator,
  ParseFilePipe,
  Post,
  UploadedFile,
  UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';

@Controller('uploads')
export class UploadController {
  @Post()
  @UseInterceptors(FileInterceptor('file'))
  uploadFile(
    @UploadedFile(
      new ParseFilePipe({
        validators: [
          new MaxFileSizeValidator({
            maxSize: 5 * 1024 * 1024, // 5 MB
          }),
        ],
      }),
    )
    file: Express.Multer.File,
  ) {
    return {
      filename: file.originalname,
      size: file.size,
    };
  }
}
```

## AI Coding Instructions

- Instantiate `MaxFileSizeValidator` with a `maxSize` value in bytes; use clear constants for readable size limits.
- Add the validator to `ParseFilePipe` alongside other validators such as `FileTypeValidator`.
- Ensure the upload interceptor, such as `FileInterceptor`, runs before attempting to validate the uploaded file.
- Do not rely on client-provided file metadata alone; configure upload limits and storage settings as additional protection.
- Use `buildErrorMessage()` behavior consistently when extending or composing file-validation error handling.
