Thursday, October 10, 2013

JavaScript File Extension Validation


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:
function Checkfiles()
    {
        var fup = document.getElementById('fileAttach');
        var fileName = fup.value;
        var ext = fileName.substring(fileName.lastIndexOf('.') + 1);

    if(ext =="doc" || ext=="docx")
    {
        return true;
    }
    else
    {
  elem1 = document.getElementById('filetype');
  elem1.innerHTML='Not Allowed file type.';  
        return false;
    }
    }

Form should look like this:
<form ... onsubmit="return checkfiles();">

You Can use like this also if you want validate one filed of form.

<input ... onChange="return checkfiles();"/>

No comments:

Post a Comment