Asp.Net Custom Validator Control to validate file size






3.42/5 (4 votes)
Asp.Net Custom Validator Control to validate file size both client side validation and server side validation
The following code is used to validate the file size before uploading the file.
We use the asp.net custom validation control to achieve this. We can use asp.net
custom validation control to validate either client side or at server side. We see
both the things for this purpose.
Asp.Net Custom Validation Control Client Side Validation to Validate File Size:
<script type ="text/javascript"> function checkfilesize(source, arguments) { arguments.IsValid = false; var axo = new ActiveXObject("Scripting.FileSystemObject"); thefile = axo.getFile(arguments.Value); var size = thefile.size; if (size > 5000) { arguments.IsValid = false; } else { arguments.IsValid = true; } } </script> <asp:FileUpload ID="FileUpload1" runat="server" />Asp.Net Custom Validation Control Server Side Validation to Validate File Size:
<asp:Button ID="Button1" runat="server" Text="Upload"/>
<asp:CustomValidator ID="NewPasswordCustomValidator" runat="server" Text="*" ToolTip="FileSize should not exceed 5kb" ErrorMessage="FileSize Exceeds the Limits.Please Try uploading smaller size files." ControlToValidate="FileUpload1" ClientValidationFunction = "checkfilesize"> <asp:ValidationSummary ID="ValidationSummary1" runat="server" />
<asp:FileUpload ID="FileUpload1" runat="server" />The C# function to validate:
<asp:Button ID="Button1" runat="server" Text="Upload"/>
<asp:CustomValidator ID="NewPasswordCustomValidator" runat="server" Text="*" ToolTip="FileSize should not exceed 5kb" ErrorMessage="FileSize Exceeds the Limits.Please Try uploading smaller size files." ControlToValidate="FileUpload1" OnServerValidate = "checkfilesize"> <asp:ValidationSummary ID="ValidationSummary1" runat="server" />
protected void checkfilesize(object source, ServerValidateEventArgs args) { string data = args.Value; args.IsValid = false; double filesize = FileUpload1.FileContent.Length; if (filesize > 5000) { args.IsValid = false; } else { args.IsValid = true; } }
I hope this simple technique would help you to perform your custom validations
Understanding The Code: The code describe is very simple and helps you achieve the task. Initially start by adding the asp.net custom server control and then define the following properties to it: 1. Text: The text to be displayed. 2. Error Message: Error message for the user. 3. ControlToValidate: Validation control on which the validation should be performed. and finally we have two things 4.OnServerValidate : the name of function if you want to validate by using your server side langauge. (or) ClientValidationFunction : the name of JavaScript function if you want to validate the client side.