The Web Blinders logo

Programming

How to Count and Validate Number of files to be uploaded with JavaScript

What if someone uploads 20 files for an input that requires single file.With out client side validations, you will be sending send all those 20 files to the server and the server will be like, All I ever asked you is for 1 file,Why are you wasting my time? To avoid such drama it is better if you do client side and server side validations.
Validating number of files selected
Demo of Validating number of files selected javascript

HOW TO COUNT NUMBER OF FILES SELECTED - JAVASCRIPT

element.files.length returns number of files selected.For example :


<input multiple="multiple" id="s" type="file" />

let ele =document.getElementById("s");
console.log(ele.files.length); // logs number of files selected

VALIDATING NUMBER OF FILES SELECTED - JAVASCRIPT

If you want only one file to be uploaded , your acceptableLengthRange will be [1,1] and for 2 to 5 files it will be [2,5]


/*
selectedFilesLength - number of files selected - ( ele.files.length )
return true if minimumNumberOfFiles <= selectedFilesLength <= maximumNumberOfFiles
*/
function validate(selectedFilesLength, acceptableLengthRange) {
    return (selectedFilesLength >= acceptableLengthRange[0] && selectedFilesLength <= acceptableLengthRange[1]);
}

You could modify below code as per your requirements.All you have to do is,to add data-file-upload-range attribute to the input element

It's value will be as follows, if you want only one file then it will 1,1 and for 3 to 5 files it will be 3,5.


class ValidateFilesSelected {
    constructor() {
        this.fileTypeInputs = document.querySelectorAll("input[data-file-upload-range]");
        this.init();
    }
    countFiles(element) {
        return element.files.length;
    }
    validate(selectedFilesLength, acceptableLengthRange) {
        return (selectedFilesLength >= acceptableLengthRange[0] && selectedFilesLength <= acceptableLengthRange[1]);
    }
    init() {
        this.fileTypeInputs.forEach((ele) => {
            ele.onchange = () => {
                let range = ele.getAttribute("data-file-upload-range").split(",");
                this.validate(this.countFiles(ele), range) ? alert("Wow ! You have selected valid number of files") : alert(`Incorrect number of files selected! Selected `);
            };
        })
    }
}
(new ValidateFilesSelected());

Check out the live demo - https://www.thewebblinders.in/demos/javascript-validating-number-of-files-selected-file-uploads.html

Need developers ?

if so, send a message.

thewebblinders@gmail.com

More Programming from our blog

SEARCH FOR ARTICLES