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.