How to Limit File Count, Size, and Type in an Input Field in JavaScript
When you provide a file input (<input type="file">) for users, it's a crucial best practice to perform client-side validation. This improves the user experience by providing immediate feedback and prevents unnecessary uploads of incorrect or oversized files. While server-side validation is still essential for security, client-side checks are the first line of defense.
This guide will teach you the three main client-side validations for a file input: how to limit the number of files, the size of each file, and the type of files that can be selected.
The Foundation: Listening to the change Event
All of our JavaScript validation logic will run inside a change event listener attached to the file input. This event fires whenever the user selects one or more files. Inside the handler, we can access the selected files via the input.files property, which is a FileList object.
HTML:
<form id="upload-form">
<input type="file" id="file-input" multiple>
<p id="validation-message" style="color: red;"></p>
<button type="submit">Upload</button>
</form>
JavaScript:
const fileInput = document.getElementById('file-input');
fileInput.addEventListener('change', function() {
const files = this.files; // Get the FileList object
// (Our validation logic will go here)
});
Limiting the Number of Selected Files
If your application should only accept a certain number of files at once, you can check the length of the FileList object.
For example, the user should not be able to select more than 3 files.
The solution is to check files.length inside the change event handler.
const fileInput = document.getElementById('file-input');
const validationMessage = document.getElementById('validation-message');
const MAX_FILES = 3;
fileInput.addEventListener('change', function() {
const files = this.files;
if (files.length > MAX_FILES) {
validationMessage.textContent = `Error: You can only upload a maximum of ${MAX_FILES} files.`;
// Clear the file input to force the user to re-select.
this.value = '';
return;
}
validationMessage.textContent = ''; // Clear any previous error message
// Proceed with other logic...
});
This provides immediate feedback to the user and clears their invalid selection, forcing them to choose again.
Limiting the Size of Selected Files
To prevent users from uploading enormous files that would strain your server, you can check the size property of each File object. The size is reported in bytes.
For example, each selected file must not exceed 2 MB in size.
The solution is to iterate through the FileList and check the size of each file.
const fileInput = document.getElementById('file-input');
const validationMessage = document.getElementById('validation-message');
const MAX_FILE_SIZE_MB = 2;
const MAX_FILE_SIZE_BYTES = MAX_FILE_SIZE_MB * 1024 * 1024;
fileInput.addEventListener('change', function() {
const files = this.files;
let oversizedFiles = [];
for (const file of files) {
if (file.size > MAX_FILE_SIZE_BYTES) {
oversizedFiles.push(file.name);
}
}
if (oversizedFiles.length > 0) {
validationMessage.textContent = `Error: The following files exceed the ${MAX_FILE_SIZE_MB} MB size limit: ${oversizedFiles.join(', ')}`;
this.value = ''; // Clear the invalid selection
return;
}
validationMessage.textContent = ''; // Clear any previous error message
});
Limiting the Allowed File Types (with the accept Attribute)
The simplest and most user-friendly way to limit file types is by using the HTML accept attribute on the <input> element. This tells the browser's file picker to only show files of the specified types.
For example, you want the user to only be able to select image files.
The solution is this is best handled directly in your HTML.
<!-- Allow any image type -->
<input type="file" accept="image/*">
<!-- Allow only specific image types -->
<input type="file" accept="image/png, image/jpeg">
<!-- Allow by file extension -->
<input type="file" accept=".pdf, .docx, .doc">
Important: The accept attribute is a user convenience, not a security measure. A savvy user can bypass this filter. You should always perform a secondary check in your JavaScript and, most importantly, on your server.
JavaScript Validation for File Type:
You can check the file.type (MIME type) or file.name (for the extension) in your change event handler.
const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
fileInput.addEventListener('change', function() {
// ...
for (const file of this.files) {
if (!allowedTypes.includes(file.type)) {
validationMessage.textContent = `Error: Invalid file type (${file.type}). Only JPEG, PNG, and GIF are allowed.`;
this.value = '';
return;
}
}
// ...
});
Conclusion
Client-side file validation is an essential part of a modern web form, providing instant feedback and improving the user experience.
- To limit the number of files, check the
input.files.lengthproperty. - To limit the file size, iterate through the
FileListand check eachfile.sizeproperty (in bytes). - To limit the file type, the best first step is the HTML
acceptattribute. Follow this with a JavaScript check on thefile.typeproperty for added robustness.
Always remember that client-side validation is a convenience, not a substitute for crucial server-side validation.