Explain Codes LogoExplain Codes Logo

How to limit the maximum files chosen when using multiple file input

javascript
file-input
multiple-file-upload
javascript-best-practices
Alex KataevbyAlex Kataev·Dec 19, 2024
TLDR

Enforce a 3-file limit on a multiple file input swiftly using JavaScript. Add an event listener to the change event of the input, count the files, and clear the input if limits are exceeded.

// The holy grail of file limits const maxFiles = 3; // Listen for changes like a nosy neighbor document.querySelector('#multiFile').addEventListener('change', function() { // If user exceeds max file limit, go nuclear and reset if (this.files.length > maxFiles) { this.value = ''; // Keep calm and don't select too many files alert(`Keep your files in check, max allowed: ${maxFiles}.`); } });
<input type="file" id="multiFile" multiple>

Enhancing user interactions

To create an engaging user experience, disable the submit button if the file limit is breached whilst using jQuery's prop() method to toggle the disabled state of the button.

// Listen for change, but not quarters, we're not a jukebox $('#multiFile').on('change', function() { let fileCount = this.files.length; // Button phobia if file overload $('#uploadBtn').prop('disabled', fileCount > maxFiles); // If the file crew gets too large, replace them if (fileCount > maxFiles) { this.value = ''; // Politely ask user to reassess their life choices alert(`You've overdosed on files, ${maxFiles} is the antidote.`); } });
<input type="file" id="multiFile" multiple> <button id="uploadBtn">Fire in the hole!</button>

Don't forget to also perform server-side validation to prevent bypassing if client-side scripts are turned off. It's a sneaky world out there!

The advanced fine-tuning

The first answer exists for a quick fix but let's supercharge it by considering additional functionality and bypass prevention.

Alert polish and file input reset

Suppose we polish our onChange event handling. Resetting file inputs might be friendlier by prompting users to reselect, rather than silently resetting it.

Limiting by file type

Use the accept attribute on input. You're not just limiting quantity; limit by quality too:

<input type="file" multiple accept=".png,.jpg,.jpeg">

Testing across ecosystems

Handle file inputs in a cross-browser compatible way. Be sure to test your implementation across varied environments for consistent behavior.

Throttling and performance

For apps juggling multiple files, maybe deploy throttling techniques or web workers to avoid blocking the UI.

By employing these additional considerations, your multiple file input becomes a Fort Knox of file limit control.