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

You could run some jQuery client-side validation to check:

$(function(){
    $("input[type='submit']").click(function(){
        var $fileUpload = $("input[type='file']");
        if (parseInt($fileUpload.get(0).files.length)>2){
         alert("You can only upload a maximum of 2 files");
        }
    });    
});​

http://jsfiddle.net/Curt/u4NuH/

But remember to check on the server side too as client-side validation can be bypassed quite easily.


On change of the input track how many files are selected:

$("#image").on("change", function() {
    if ($("#image")[0].files.length > 2) {
        alert("You can select only 2 images");
    } else {
        $("#imageUploadForm").submit();
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<strong>On change of the input track how many files are selected:</strong>
<input name="image[]" id="image" type="file"  multiple="multiple" accept="image/jpg, image/jpeg" >

Another possible solution with JS

function onSelect(e) {
    if (e.files.length > 5) {
        alert("Only 5 files accepted.");
        e.preventDefault();
    }
}

Tags:

Html

File