#javascript #validation #security

Client-side validation before uploading an excel file

Validation is one of the major parts of web development. But sometimes it can be a ball buster especially when it comes to validating file uploads.

Below is a simple piece of code through which we can validate the file type before upload. You may or may not need a server-side validation after that. It’s totally up to you and your system.

Here is the code.

Html :

<input type="file" id="file" onchange="checkfile(this);" name="file" required>


    function checkfile(sender) {
        var validExts = [".xlsx", ".xls"];
        var fileExt = sender.value;
        fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
        if (validExts.indexOf(fileExt) < 0) {
            alert("Invalid file selected, valid files are of " +
                validExts.toString() + " types.");
            return false;
        } else return true;

The above code can be extended for any file. Just replace your desired file extensions in the “validExts” array and you are good to go.