validateFileList
validateFileList function processes a list of uploaded files, validating each file against:
- Maximum file size in bytes (if provided)
- Accepted file types (based on the
acceptattribute)
This function utilized by MUIFileUploader ensures only files meeting the required criteria are passed for further processing.
type ValidateFileListOptions = {
accept?: string,
maxSize?: number,
maxFiles?: number
}
type ProcessFilesResult = {
acceptedFiles: File[];
rejectedFiles: {
file: File;
errors: FileUploadError[];
}[];
}
function validateFileList(
fileList: FileList | File[],
options?: ValidateFileListOptions
): ProcessFilesResultUsage#
import { validateFileList } from '@nish1896/mui-components/form-helpers';Parameters#
fileList: The set of input files to run this validation against.options: Validation options used when processing the file list.accept— Optional string specifying the allowed file types or extensions, following the standard input[type="file"]acceptattribute format (for example,.png, .jpg, image/*). Files that do not match the specified criteria will be added torejectedFiles.maxSize— Optional maximum file size in bytes. Files exceeding this limit will be added torejectedFiles.maxFiles— Optional maximum number of files allowed. If the number of valid files exceeds this limit, the additional files will be added torejectedFileswith aFILE_LIMIT_EXCEEDEDerror and excluded fromacceptedFiles.
Returns#
-
acceptedFiles— Files that passed validation (File[]). -
rejectedFiles— Files that failed validation, along with the reasons for rejection, and is of the type:type FileUploadErrorDetails = { /** File that failed validation. */ file: File; /** Validation errors reported for the file. */ errors: FileUploadError[]; };Possible
FileUploadErrorvalues:FILE_SIZE_EXCEEDEDFILE_TYPE_NOT_ALLOWEDFILE_LIMIT_EXCEEDED
:::warning
The validateFileList method signature and return value have changed in v4.
- The function now accepts a single options object instead of multiple positional arguments.
- The returned
errorsarray has been removed. Validation errors are now returned as part ofrejectedFiles.
If you are using this utility directly in your application, update existing calls accordingly:
- const {
- acceptedFiles,
- rejectedFiles,
- errors
- } = validateFileList(fileList, '*', 5 * 1024 * 1024, 3);
+ const {
+ acceptedFiles,
+ rejectedFiles
+ } = validateFileList(fileList, {
+ accept: '*',
+ maxSize: 5 * 1024 * 1024,
+ maxFiles: 3
+ });:::
Examples#
// Allow any file, but max allowed size for each file should be 5 MB.
validateFileList(fileList, { accept: '*', maxSize: 5 * 1024 * 1024 });
// Allow only image mimetype
validateFileList(fileList, { accept: 'image/*' });
// Allow at max 3 files
validateFileList(fileList, { maxFiles: 3 });