Multiple File Validation
You'll learn how to validate every file in a FileList when users select multiple files at once, ensuring all files meet your requirements before processing.
The Challenge of Many Files
When a user selects multiple files (using the multiple attribute on a file input or dropping several files at once), you receive a FileList object containing all files. You can't just validate the first file and call it a day—each file must pass validation individually.
Think of it like airport security: even if one passenger has valid documents, every person in the group must be checked. One invalid file should not slip through just because others are valid.
Iterating Through the FileList
Since FileList is array-like (but not a true array), you can loop through it with a standard for loop or convert it to an array:
const fileInput = document.getElementById('upload');
const files = fileInput.files;
// Validate each file
for (let i = 0; i < files.length; i++) {
const file = files[i];
// Check file size (5MB max)
if (file.size > 5 * 1024 * 1024) {
alert(`${file.name} exceeds 5MB limit`);
return;
}
// Check file type
if (!file.type.startsWith('image/')) {
alert(`${file.name} is not an image`);
return;
}
}
// All files are valid
console.log('All files passed validation!');
The key is checking every file against your criteria (size, type, extension, or even dimensions for images). If any single file fails, you can reject the entire batch or provide detailed feedback about which files are problematic.
Key Takeaway: Always validate each file in a FileList individually using a loop, applying all necessary checks (size, type, extension) to every file before proceeding with uploads or processing.