Wednesday, November 27, 2013

Javascript to Validate File Size of FileUpload Control in

Using Javascript code file size of file upload control can be checked and if the uploaded file size is more than the required size then custom message can be displayed to the user. To validate file size use the custom validator and set the ClientValidationFunction to javascript function which will check the file size and set the ControlToValidate property  of custom validator control to id of File Upload Control.

Note the file size which is compared in this example must be in kb. In this example If uploaded image  size is greater than 100kb(102400 bytes) then custom message would be displayed. You can change this value according to your requirement.

Sample Javascript Code to validate File Size of FileUpload Control:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!DOCTYPE html>

<html xmlns="">
<head runat="server">
 <script src="//"></script>
<script type="text/javascript">
function checkfilesize(source, arguments)
 arguments.IsValid = false;
 var size = document.getElementById("<%=fupuploadimg.ClientID%>").files[0].size;
 if (size > 102400) {
 arguments.IsValid = false;
 return false;

  else {

arguments.IsValid = true;
return true;


  <form id="form1" runat="server">
  <div style="float:left;margin-left:100px; margin-top:50px;">
 <b>Upload File:</b> &nbsp; <asp:FileUpload ID="fupuploadimg" runat="server"  />
      &nbsp;&nbsp;&nbsp;&nbsp;  <asp:CustomValidator id="cvvalidate" runat="server" 
  ToolTip="FileSize should not exceed 1MB" Style="color: #FF0000;
  display: inline; float: left; font-family: arial; font-size: 13px; margin-left: 100px;
  margin-top:10px;" ValidationGroup="a"
  ErrorMessage="FileSize Exceeds the Limits."
 ClientValidationFunction = "checkfilesize"></asp:CustomValidator>


  1. This option is quite appealing. Is there a way to apply this approach if the user's browser does not support the .file[0] attribute? I can only get the .value attribute from my FileUpload object. I am also unable to create an ActiveXObject of type Scripting.FileSystemObject. Thanks for the consideration.