File upload validation for file type with JavaScript

Not only will this JavaScript code validate that a file has been selected in your upload control, but it will also examine the file extension and restrict the file that may be uploaded to specific file types. It is essential for security and very helpful for ensuring that files are of the correct format.

We first loop through the HTML elements of the page looking for any that are of "TYPE=FILE." We then evaluate (using string parsing) the file extension from the value property of upload control and reject/clear the file upload if it does not meet our criteria.

This code can be used as a function in the JSHeader or in the onSubmit with a minor tweak.

Please note that there is still nothing to stop the user from changing the file?s extension in which case they would be able to get around the validation.

This code has been successfully tested on both IE and Navigator and for both PC and Mac. However, a Mac user would be required to name the file with the appropriate file extension.


for( i=0 ; i
 

    Requires Free Membership to View

This was first published in July 2001

Disclaimer: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.