When using <input type="file" multiple>
is it possible to ask users to input at least n
files?
Ex: <input type="file" min=5 multiple>
JavaScript is required. Add an event listener to listen for the change
event on the input, and check the number of uploaded files with .files.length
.
var uploader = document.querySelector('input');
var error = document.querySelector('p');
uploader.addEventListener("change", function(){
if(uploader.files.length < 5){
error.style.display='block';
}
})
#error{
display:none;
color:red;
}
<input type="file" multiple/>
<p id="error">Please upload at least 5 files</p>
Using it in a form
to prevent submission if the number of uploaded files is less than 5:
var uploader = document.querySelector('input');
var error = document.querySelector('p');
function validate(){
if(uploader.files.length < 5){
error.style.display='block';
return false;
}
}
#error{
display:none;
color:red;
}
<form action="somewhere.php" onsubmit="return validate()">
<input type="file" multiple/>
<p id="error">Please upload at least 5 files</p>
<button>Submit files</button>
</form>