Overview
The file validation utilities provide a robust way to validate file inputs against various constraints including file type, size, count limits, and custom validation logic. Both synchronous and asynchronous variants are available.Import
Functions
handleFileValidation
Validates files synchronously against the provided settings.Signature
Parameters
The files to validate.
Array of existing files to check against for duplicates and max count.
Validation rules configuration.
Array of allowed file extensions or MIME types (e.g.,
[".jpg", ".png", "image/*"]).Maximum file size. Can be specified in bytes or using an object with kb/mb/gb properties.
Maximum number of files allowed (including existing files).
Whether to reject duplicate files. Default is
false.Custom validation function. Return an error object to reject the file, or
null/undefined to accept.Callbacks for handling validation events.
Called when an individual file passes validation.
Called after all validation if any files passed.
Called when an individual file fails validation.
Called after all validation if any files failed.
Return Value
handleFileValidationAsync
Async version ofhandleFileValidation that supports async validators and hooks.
Signature
handleFileValidation, but the validator and all hooks can return Promises.
Helper Functions
formatBytes
Formats bytes into a human-readable string.toBytes
Converts size object to bytes.generateFileID
Generates a unique ID for a file.Usage Examples
Basic File Validation
With Validation Hooks
Custom Validator
Async Validation
Duplicate Detection
React Integration
Error Codes
| Code | Description |
|---|---|
"file-too-large" | File exceeds maxFileSize |
"invalid-file-type" | File type not in allowedFileTypes |
"too-many-files" | Files exceed maxFileCount |
"duplicate-file" | File already exists (when rejectDuplicateFiles is true) |
"custom-validation-failed" | Custom validator rejected the file |
Types
FileMeta
FileValidationErrorContextEach
Notes
- File size can be specified as a number (bytes) or using
{ mb: 5 },{ kb: 500 }, etc. - File types can be MIME types (
"image/jpeg") or extensions (".jpg") - Wildcards are supported for MIME types (
"image/*","video/*") - Duplicate detection is based on file name and size
- Use async variant when validation requires I/O operations (reading file contents, API calls, etc.)