Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

file upload validation with javascript

Posted by Viral Sarvaiya on March 13, 2009

step 1 : Make a default.aspx page

put this script in to head section of html page.


function valid_file()


alert(‘Please Upload Image File’);
return false;


function ChkFile(txtfield)
var filename,filenamelen
var fileext,fileextlen
var allowedtypes = [“.jpg”,”.JPG”,”.jpeg”,”.JPEG”,”.BMP”,”.bmp”]
var dotpos
filename = txtfield.value
filenamelen = filename.length
dotpos = filename.lastIndexOf(“.”)
fileextlen = (filenamelen – dotpos – 1)

if (fileextlen >= 3 && fileextlen <= 4) //this allows files with a min of 3 and max of 4 chars in their extension
fileext = filename.substring(dotpos,filenamelen)
//alert (fileext)
for(var ctr=0;ctr<allowedtypes.length;ctr++)

if(allowedtypes[ctr] == fileext)
return true;
//alert(“Only JPG/JPEG/GIF type picture files are allowed.\n Please select a valid file type.”)

//alert(“The file you have selected is not a valid picture file.\nPlease select a different file.”)

return false


step 2 :On the  default.aspx.vb page

add this code in to page load function

dont put this file in ispostback block

btnsubmit..Attributes.Add(“onclick”, “javascript:return valid_file();”)


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: