Validate file upload control using Custom Validator

Madhu.B.Rokkam
Posted by Madhu.B.Rokkam under ASP.NET category on | Points: 40 | Views : 5404
1. Code in the ASPX page. Add a file upload control and a custom validator

<form id="form1" runat="server">
<asp:FileUpload ID="fileupload" runat="server" />
<asp:CustomValidator ID="cv" runat="server" ControlToValidate="fileupload"
ErrorMessage="Message" OnServerValidate="cv_ServerValidate" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
</form>


2. Add a server side validator function for validation of upload control
protected void cv_ServerValidate(object source, ServerValidateEventArgs args)
{
if (System.IO.Path.GetExtension(fileupload.FileName) == ".pdf")
{
if (fileupload.FileBytes.Length > 20971520)
{
cv.ErrorMessage = "File size exceeds maximum limit 20 MB.";
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
else
{
cv.ErrorMessage = "File type should be pdf.";
args.IsValid = false;
}
}


3. You can implement your logic to upload a file in btnUpload_Click event

protected void btnUpload_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
// your logic here
}
}

Comments or Responses

Login to post response