magic is happening
Read Time45Seconds

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>

JavaScript:

<script>
    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.");
            document.getElementById("form-id").reset();
            return false;
        } else return true;
    }
</script>

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.

0 0

About Post Author

samgan

samgan excel at solving complex problems involving logic and step by step breakdown of the problem. In addition, to develop complex algorithms, he specialize in problem framing, systems design, and product development strategy. Sometimes he also enjoy public speaking.
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleppy
Sleppy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

Leave a Reply

Your email address will not be published. Required fields are marked *

Close
Secondary Navigation
Social profiles