Manage Learn to apply best practices and optimize your operations.

File upload validation for file type with JavaScript

It is essential for security and very helpful for ensuring that files are of the correct format.

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<document.forms[0].elements.length ; i++) {
	a = document.forms[0].elements[i].type ;
	if( a == 'file' ) {
		var fullfilepath = document.forms[0].elements[i].value; 
		if( fullfilepath == '' ) {
			alert('You must select a file or click cancel');
		} else {
			//--  get file name
			var arry = fullfilepath.split( "" );
			filenm1 = arry[arry.length-1];
			var arry1 = filenm1.split( "/" );
			filenm = arry1[arry1.length-1];	
			//-- get file extension
			var arryext = filenm.split( "." );
			ext = arryext[arryext.length-1];
			extlwr = ext.toLowerCase();
			if( extlwr == 'gif' || extlwr == 'jpg' || extlwr == 'jpeg' ) {

			} else {
				alert( 'The file must be a GIF or JPEG and have the appropriate file extension.');

Dig Deeper on Lotus Notes Domino Administration Tools

  • Favorite iSeries cheat sheets

    Here you'll find a collection of valuable cheat sheets gathered from across the iSeries/ community. These cheat ...