Following code validates the file extension as soon as file is selected. If the extension/s are not as per requirement this will reset the input box with alert.
//Javascript code -- add following code into html head.
<script>
var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];
function ValidateSingleInput(oInput) {
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("Invalid file. Only image files are allowed. (.jpg .jpeg .bmp .gif .png)");
oInput.value = "";
return false;
}
}
}
return true;
}
</script>
// HTML input file code
<input type="file" onchange="ValidateSingleInput(this);" name="avatarUrl"/>
Comments
Post a Comment