Kind: Class
Source: packages/common/pipes/file/file-validator.interface.ts
Part of: Common
Interface describing FileValidators, which can be added to a ParseFilePipe
FileValidator defines the contract for validators used by ParseFilePipe to inspect uploaded files. Implementations provide validation logic through isValid() and return a user-facing failure message through buildErrorMessage() when validation fails.
Methods
| Method | Signature | Returns |
|---|---|---|
isValid | `isValid(file: TFile | TFile[] |
buildErrorMessage | buildErrorMessage(file: any) | string |
Diagram
mermaidgraph LR A[Uploaded file] --> B[ParseFilePipe] B --> C[FileValidator.isValid] C -->|Valid| D[Controller handler] C -->|Invalid| E[FileValidator.buildErrorMessage] E --> F[Validation error response]
Usage
tsimport {
FileValidator,
ParseFilePipe,
UploadedFile,
UseInterceptors,
FileInterceptor,
Controller,
Post,
} from '@nestjs/common';
class AllowedMimeTypeValidator implements FileValidator {
isValid(file?: Express.Multer.File): boolean {
return file?.mimetype === 'image/png';
}
buildErrorMessage(): string {
return 'Only PNG image uploads are allowed.';
}
}
@Controller('uploads')
export class UploadController {
@Post()
@UseInterceptors(FileInterceptor('file'))
upload(
@UploadedFile(
new ParseFilePipe({
validators: [new AllowedMimeTypeValidator()],
}),
)
file: Express.Multer.File,
) {
return {
filename: file.originalname,
mimetype: file.mimetype,
};
}
}
AI Coding Instructions
- Implement both
isValid()andbuildErrorMessage()for every customFileValidator. - Keep
isValid()focused on validation and return either a boolean orPromise<boolean>for asynchronous checks. - Return clear, client-safe messages from
buildErrorMessage(); avoid exposing internal storage or security details. - Register validator instances in
ParseFilePipethrough itsvalidatorsoption. - Account for missing files in validators when the upload field may be optional.
Was this page helpful?