Validation of file extension before uploading file Validation of file extension before uploading file jquery jquery

Validation of file extension before uploading file


It's possible to check only the file extension, but user can easily rename virus.exe to virus.jpg and "pass" the validation.

For what it's worth, here is the code to check file extension and abort if does not meet one of the valid extensions: (choose invalid file and try to submit to see the alert in action)

var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];    function Validate(oForm) {    var arrInputs = oForm.getElementsByTagName("input");    for (var i = 0; i < arrInputs.length; i++) {        var oInput = arrInputs[i];        if (oInput.type == "file") {            var sFileName = oInput.value;            if (sFileName.length > 0) {                var blnValid = false;                for (var j = 0; j < _validFileExtensions.length; j++) {                    var sCurExtension = _validFileExtensions[j];                    if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {                        blnValid = true;                        break;                    }                }                                if (!blnValid) {                    alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));                    return false;                }            }        }    }      return true;}
<form onsubmit="return Validate(this);">  File: <input type="file" name="my file" /><br />  <input type="submit" value="Submit" /></form>