Tuesday, November 16, 2010

File Upload control validation using Javascript

We often used to validate Fileupload control by file extension validation at server side.It is little bit time taking process but secure. If we want to validate file upload control with some known file extensions at client side, we need to use javascript.

See the below example to validate file upload control using javascript :


In aspx page header section just write the following javascript code:


<script type ="text/javascript">

// Declare known file extensions in an array
var validFilesTypes=["bmp","gif","png","jpg","jpeg","doc","xls"];

function ValidateFile()
{
var file = document.getElementById("<%=FileUpload1.ClientID%>");
var label = document.getElementById("<%=Label1.ClientID%>");
var path = file.value;
var ext=path.substring(path.lastIndexOf(".")+1,path.length).toLowerCase();
var isValidFile = false;
for (var i=0; i<validFilesTypes.length; i++)
{
if (ext==validFilesTypes[i])
{
isValidFile=true;
break;
}
}
if (!isValidFile)
{
label.style.color="red";
label.innerHTML="Invalid File. Please upload a File with" +
" extension:\n\n"+validFilesTypes.join(", ");
}
return isValidFile;
}
</script>


In aspx page body section :

<asp:fileupload id="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload"
OnClientClick = "return ValidateFile();" />
<asp:Label ID="Label1" runat="server" Text="" />

Hope this is helpfull..!

1 comment:

  1. I need to validate size of the file in java script if there pls update it and remind me at refreshrk@gmail.com

    ReplyDelete