In this article I will explain with an example, how to validate File in INPUT Type File (FileUpload) using JavaScript in HTML.
 
 
HTML Markup
The HTML Markup consists of:
FileUpload – For selecting file.
Button – For validating selected file.
The Button has been assigned with a JavaScript onclick event handler to call ValidateFile function.
SPAN – For displaying error message.
<input id="fuUpload" type="file" />
<input type="submit" value="Submit" onclick="return ValidateFile()" />
<br />
<span id="lblMessage" style="color:red;"></span>
 
 
Validating File in INPUT Type File (FileUpload) using JavaScript
When the Submit button is clicked, the ValidateFile JavaScript function gets called.
Inside the ValidateFile JavaScript function, the file extension of the selected file is determined and an Array of valid file type is defined.
Then, the file extension is verified whether exists or not in the Array using the Array.includes function and returned value is set in isValidFile variable.
The following Array can be easily set with valid file extensions as per your requirement.
var validFilesTypes = ["doc", "docx", "pdf"];
 
Finally, if isValidFile variable is FALSE then, the error message is set to the SPAN element and FALSE is returned.
<script type="text/javascript">
    function ValidateFile() {
        var path = document.getElementById("fuUpload").value;
        var label = document.getElementById("lblMessage");
        label.innerHTML = "";
        var extension = path.substring(path.lastIndexOf(".") + 1, path.length).toLowerCase();
        var validFilesTypes = ["doc", "docx", "pdf"];
        var isValidFile = validFilesTypes.includes(extension);
        if (!isValidFile) {
            label.innerHTML = "Invalid File. Please upload file with extension: " + validFilesTypes.join(", ") + ".";
            return false;
        }
    }
</script>
 
 
Screenshot
Validate File in INPUT Type File (FileUpload) using JavaScript in HTML
 
 
Browser Compatibility
The above code has been tested in the following browsers.
Microsoft Edge  FireFox  Chrome  Safari  Opera
* All browser logos displayed above are property of their respective owners.
 
 
Demo
 
 
Downloads