Check File Extension using JS

In this tutorial we will see how to check the extension of the uploaded file in a form using Javascript. In the example below user is allowed to upload only zip,rar and tar.gz file extensions.

You can edit the simple script to allow other extensions.

Check out the script given below - 


 

<html>

<head>

<script type="text/javascript">

function extCheck()

{

var elem= document.getElementById("file");

var re_text = /\.rar|\.tar.gz|\.zip/i;

  if (elem.value.search(re_text) == -1)

    {

alert ("Incorrect File extension\n Should be zip,rar,etc ");       

  file.form.reset();

        return false;

    }

  else return true;

}

</script>

</head>

<body>

<form id="bOtFfOrm" name="bOtfOrm" action="some.php">

Upload a file with extensions zip,rar and tar.gz only.

<input type="file" id="file" name="file" onChange="extCheck()"/>

</form>

</body>

</html>

A demo of the above example is given below. Try it out!

Upload a file with extensions zip,rar and tar.gz only.