Article
    C#
    ADO.Net
    .NET
    ASP.Net & Web Forms
    Custom Controls
    Web Development
    Exception Handling
    XML
    Database
    Security in .Net
    Testing
    Web Services
    Windows Services
    Windows Controls
    WCF
    AJAX
    WPF
    XAML
    Reporting
    Setup
    VB.Net
    LINQ
    JQuery
    SilverLight
    JavaScript
    HTML5
    Crystal Report
    Cloud Computing
    Share Point
    Visual C++
    MVC
    Android
    PHP
    Java
    HTML
    WordPress
    Joomla
    Products
    Drupal
    Windows Phone
    JSON
    LightSwitch
    iPhone/iPad
    Ruby on Rails
    IIS 7
    Windows 8
    CSS/CSS3
    Excel
    MS Access
    Shortcut Keys
    Visual SourceSafe
    Team Foundation Server
    APIs
Follow Us
Follow _MindStick_ on Twitter View MindStick Software's LinkedIn profile View MindStick Software's Facebook profile
Top Contributor
Advertisement
Advertise with Us
Mindstick
Article Article  Forum Forum  Blog Blog  Quiz Quiz  Beginner Beginner  Careers Careers  Contact Contact  Login Login  
Home | Product | Services | About Us | Interview | DeveloperSection | Submit an Article | Submit Blog

Home >> ASP.Net & Web Forms >> Validating FileUpload control for specific file type and required field.
Validating FileUpload control for specific file type and required field.
Validating FileUpload control for specific file type and required field.


by Haider M Rizvi on 1/1/2011 8:48:52 PM

Views: 27771       Comments: 15

Validating FileUpload control for specific file type and required field.

In this article I am going to explain how we can check and validate user for uploading only certain files and making uploading of file to be must for submission of form.

For validating for required field we have to use RequiredFieldValidator and for validating for file types we’ll have to use RegularExpressionValidator. But, before starting we should have brief idea about the controls required.

Before starting about validating FileUpload we must have brief idea about FileUpload control and Validation Controls of ASP.Net

FileUpload Control: FileUpload control is used for uploading file to the server from the client side.

For detailed reading about FileUpload visit:

http://mindstick.com/Articles/c323d0d8-495e-46c6-a12d-024908aa7a29/

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload.aspx

RequiredFieldValidator: With this control, the validation fails if the input value does not change from its initial value. By default, the initial value is an empty string ("").

For more details visit: http://mindstick.com/Articles/34e5fb73-9bdf-4850-9a3e-e10a5f428148/

RegularExpressionValidator: The RegularExpressionValidator control is used to ensure that an input value matches a specified pattern. The validation will not fail if the input control is empty. Use the RequiredFieldValidator control to make the field required.

 

For more details about RegularExpressionValidator visit following link:

http://www.mindstick.com/Articles/46ad6aee-13e6-4aad-a24a-268d20467f9f/?RegularExpressionValidator%20Control%20in%20ASP.Net

Validating FileUpload Control in ASP.Net

Validating File Upload Control certain file types. Here in the example below I am using RegularExpressionValidator to accomplish my task.

<asp:FileUpload ID="FileUpload1" runat="server" />

 

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Only .doc , .docx or .txt files are allowed."

ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.doc|.docx|.txt)$"

ControlToValidate="FileUpload1">*</asp:RegularExpressionValidator>

 

Here, regular expression for .doc,  .docx,  .txt files is:

"^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.doc|.docx|.txt)$"

If you want some more or other files type to be uploaded then you can replace or add more extension with the above mentioned extensions. Suppose you want your user to upload only .pdf file then you Regular expression for that will be:

"^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.pdf)$"

But, this does not mean that user will be forced to upload file, this validation is only performed if user tries to upload file. If you want to make uploading of file mandatory then you have to use Required Field Validator.

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="You have not uploaded your file" ControlToValidate="FileUpload1">* </asp:RequiredFieldValidator>

 

The code above will validate FileUpload1 for required field.

Report Abuse Form
Reason:    
 


Validation
by John Smith 3/27/2011 3:41:05 AM
Really useful Article Haider.
Report Abuse

Validator syntax in my script
by Shoeb Khan 12/28/2011 9:53:36 AM
Hi,

In my script below, where would I paste the validator?

<%@ Page Language="VB" %>
<%@ Import Namespace="System.IO" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server" >
   
    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
        LblError.Visible = False
        Dim strUploadsDirectoryPath As String = Session("FileUploadPath")
        Dim strLatestGenPONum As String = Session("LatestGeneratedPONum")
        Dim strCompleteFilepath As String = filUpload.PostedFile.FileName
        Dim strActualFileName As String = System.IO.Path.GetFileName(strCompleteFilepath)
        Dim myFileinfo As New FileInfo(strUploadsDirectoryPath & "\" & strLatestGenPONum & strActualFileName)
       
        LblError.Text = ""
                           
        If strActualFileName = "" Then
            LblError.Visible = True
            LblError.Text = "Please enter a valid Resource or Browse to the location"
            Session("FileUploadStatus") = "False"
        Else
            Try
                         
                If myFileinfo.Exists = False Then
            Dim fso, f
                     fso = CreateObject("Scripting.FileSystemObject")
            If fso.FolderExists(strUploadsDirectoryPath + strLatestGenPONum) = false Then 
            f = fso.CreateFolder(strUploadsDirectoryPath + strLatestGenPONum)
            End If
               
            filUpload.PostedFile.SaveAs(strUploadsDirectoryPath + strLatestGenPONum + "\" + strActualFileName)
                LblError.Visible = True
                    LblError.Text = "File physically Uploaded. Please remember to - confirm your attachment..."
                    Session("FileUploadStatus") = "True"
                    Session("DocumentName") = strActualFileName
           
                Else
                    LblError.Visible = True
                    LblError.Text = "Uploaded file already exists"
                    Session("FileUploadStatus") = "False"
                    Session("DocumentName") = ""
                End If
           
            Catch ex As Exception

                LblError.Visible = True
                LblError.Text = ex.ToString()
                Session("FileUploadStatus") = "False"

            End Try
           
        End If

      

    End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Upload File</title>
    <style runat="server">
        .buttonStyleNew{
        border:2px solid #333333;
        font-size:12px;
        color:#FFFFFF;
        background-color:#656565;
        font-family:Arial, Helvetica, sans-serif;
        }
        .UploadNew{
        border:2px solid #333333;
        font-size:12px;
        color:#FFFFFF;
        font-family:Arial, Helvetica, sans-serif;
        }
    </style>
</head>
<body>
    <form id="FrmUpload" runat="server" method="post">
    <div>

    <asp:FileUpload runat="server" ID="filUpload" CssClass="UploadNew" Width="364px" ForeColor="Black" />&nbsp;&nbsp;&nbsp;&nbsp;<asp:Button ID="btnUpload" runat="server" Text="Upload File" CssClass="buttonStyleNew"/><br />
        &nbsp;<asp:Label runat="server" ID="LblError" Visible="false" ForeColor="red" Font-Size="small" Font-Bold="false"></asp:Label></div>
    </form>
</body>
</html>
Report Abuse

Validating FileUpload control for specific file type and required field.
by Haider M Rizvi 12/29/2011 1:01:55 AM

Hi Shoeb Khan,

You can use paste your validator anywhere between <body> </body> tag, all you need to do is to pass the name of your FileUpload control in ControlToValidate property of validator.

<asp:FileUpload runat="server" ID="filUpload" CssClass="UploadNew" Width="364px" ForeColor="Black" />

<asp:RegularExpressionValidator ID="RegularExpressionValidator1"runat="server"ErrorMessage="Only .doc , .docx or .txt files are allowed." ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.doc|.docx|.txt)$" ControlToValidate="filUpload">*</asp:RegularExpressionValidator>

Hope this will solve your problem.

Report Abuse

Validating FileUpload control for specific file type and required field.
by Shoeb Khan 12/29/2011 3:54:43 AM
Below is the changes I have made. It works, but the error message is not displayed. It only display '*' if wrong file type is selected.


<%@ Page Language="VB" %>
<%@ Import Namespace="System.IO" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server" >
   
    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
        LblError.Visible = False
        Dim strUploadsDirectoryPath As String = Session("FileUploadPath")
    Dim strPOYear As String = Session("POYear")
        Dim strLatestGenPONum As String = Session("LatestGeneratedPONum")
        Dim strCompleteFilepath As String = filUpload.PostedFile.FileName
        Dim strActualFileName As String = System.IO.Path.GetFileName(strCompleteFilepath)
        Dim myFileinfo As New FileInfo(strUploadsDirectoryPath & strPOYear & "\" & strLatestGenPONum & "\" & strActualFileName)
    'Response.Write("PATH : " & strUploadsDirectoryPath & strPOYear & "\" & strLatestGenPONum & "\" & strActualFileName)       

        LblError.Text = ""
                           
        If strActualFileName = "" Then
            LblError.Visible = True
            LblError.Text = "Please enter a valid Resource or Browse to the location"
            Session("FileUploadStatus") = "False"
        Else
            Try
                         
                If myFileinfo.Exists = False Then
            Dim fso, f
                     fso = CreateObject("Scripting.FileSystemObject")
            If fso.FolderExists(strUploadsDirectoryPath + strPOYear + "\" + strLatestGenPONum) = false Then 
            f = fso.CreateFolder(strUploadsDirectoryPath + strPOYear + "\" + strLatestGenPONum)
            End If
               
            filUpload.PostedFile.SaveAs(strUploadsDirectoryPath + strPOYear + "\" + strLatestGenPONum + "\" + strActualFileName)
                LblError.Visible = True
                    LblError.Text = "File physically Uploaded. Please remember to - confirm your attachment..."
                    Session("FileUploadStatus") = "True"
                    Session("DocumentName") = strActualFileName
           
                Else
                    LblError.Visible = True
                    'LblError.Text = "Uploaded file already exists"
            LblError.Text = "file already exists..Overwriting"
                    'Session("FileUploadStatus") = "False"
                    'Session("DocumentName") = ""
            Session("FileUploadStatus") = "True"
                    Session("DocumentName") = strActualFileName
                End If
           
            Catch ex As Exception

                LblError.Visible = True
                LblError.Text = ex.ToString()
                Session("FileUploadStatus") = "False"

            End Try
           
        End If

      

    End Sub

</script>


<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Upload File</title>
    <style runat="server">
        .buttonStyleNew{
        border:2px solid #333333;
        font-size:12px;
        color:#FFFFFF;
        background-color:#656565;
        font-family:Arial, Helvetica, sans-serif;
        }
        .UploadNew{
        border:2px solid #333333;
        font-size:12px;
        color:#FFFFFF;
        font-family:Arial, Helvetica, sans-serif;
        }
    </style>
</head>
<body>
    <form id="FrmUpload" runat="server" method="post">
   <div>
<asp:FileUpload ID="filUpload" runat="server" CssClass="UploadNew" Width="364px" ForeColor="Black" />&nbsp;&nbsp;&nbsp;&nbsp;<asp:Button ID="btnUpload" runat="server" Text="Upload File"

CssClass="buttonStyleNew"/><br />&nbsp;<asp:Label runat="server" ID="LblError" Visible="False" ForeColor="red" Font-Size="small" Font-Bold="false"></asp:Label><asp:RegularExpressionValidator

ID="RegularExpressionValidator1" runat="server" ErrorMessage="Only .doc , .docx or .txt files are allowed." ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+

(.doc|.docx|.txt|.pdf|.xls|.xlsx|.ppt|.zip|.jpg|.png|.tiff|.PDF|.DOC|.DOCX|.JPG|.JPEG|.jpeg|.XLS|.XLSX|.PPT|.ZIP|.RAR|.rar|.TIFF)$" ControlToValidate="filUpload">*</asp:RegularExpressionValidator> </div>
    </form>
</body>
</html>
Report Abuse

Validating FileUpload control for specific file type and required field.
by Haider M Rizvi 12/29/2011 4:04:19 AM

All you need to do is to remove * from the validator.

Instead of validator below :

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Only .doc , .docx or .txt files are allowed." ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.doc|.docx|.txt)$" ControlToValidate="filUpload">*</asp:RegularExpressionValidator>

Use this:

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Only .doc , .docx or .txt files are allowed." ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.doc|.docx|.txt)$" ControlToValidate="filUpload"></asp:RegularExpressionValidator>

The only difference in both of them is that one have “*” sign and another don’t have.

Report Abuse

Validating FileUpload control for specific file type and required field
by Shoeb Khan 12/29/2011 9:27:24 AM
Thats great......Thanks for all that support. Much appreciated :)

Let me know if I can ask for a VB code for a  calendar (not a dropdown calendar)
Report Abuse

Asking questions.
by Haider M Rizvi 12/29/2011 9:42:45 AM

You can ask you question in our forum section.

http://www.mindstick.com/mindForum/Topic.aspx

Report Abuse

Validating FileUpload control for specific file type and required field
by Shoeb Khan 1/3/2012 4:24:42 AM
The script works fine. But after upload is successful, the message 'only .doc,............' appears again, which i want to avoid.

Report Abuse

Validating FileUpload control for specific file type and required field
by Haider M Rizvi 1/3/2012 7:32:14 AM
Hi Shoeb,

I think you must have missed something.
Could you please post your latest code here.

Thanks,
Report Abuse

Validating FileUpload control for specific file type and required field
by Shoeb Khan 1/3/2012 11:24:19 AM
Hi Haider,

here it is...

-------


<%@ Page Language="VB" %>
<%@ Import Namespace="System.IO" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server" >
   
    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
        LblError.Visible = False
        Dim strUploadsDirectoryPath As String = Session("FileUploadPath")
    Dim strPOYear As String = Session("POYear")
        Dim strLatestGenPONum As String = Session("LatestGeneratedPONum")
        Dim strCompleteFilepath As String = filUpload.PostedFile.FileName
        Dim strActualFileName As String = System.IO.Path.GetFileName(strCompleteFilepath)
        Dim myFileinfo As New FileInfo(strUploadsDirectoryPath & strPOYear & "\" & strLatestGenPONum & "\" & strActualFileName)
    Response.Write("PATH : " & strUploadsDirectoryPath & strPOYear & "\" & strLatestGenPONum & "\" & strActualFileName)       

        LblError.Text = ""
                           
        If strActualFileName = "" Then
            LblError.Visible = True
            LblError.Text = "Please enter a valid Resource or Browse to the location"
            Session("FileUploadStatus") = "False"
        Else
            Try
                         
                If myFileinfo.Exists = False Then
            Dim fso, f
                     fso = CreateObject("Scripting.FileSystemObject")
            If fso.FolderExists(strUploadsDirectoryPath + strPOYear + "\" + strLatestGenPONum) = false Then 
            f = fso.CreateFolder(strUploadsDirectoryPath + strPOYear + "\" + strLatestGenPONum)
            End If
               
            filUpload.PostedFile.SaveAs(strUploadsDirectoryPath + strPOYear + "\" + strLatestGenPONum + "\" + strActualFileName)
                LblError.Visible = True
                    LblError.Text = "File physically Uploaded. Please remember to - confirm your attachment..."
                    Session("FileUploadStatus") = "True"
                    Session("DocumentName") = strActualFileName
           
                Else
                    LblError.Visible = True
                    LblError.Text = "Uploaded file already exists"
                    Session("FileUploadStatus") = "False"
                    Session("DocumentName") = ""
           
                End If
           
            Catch ex As Exception

                LblError.Visible = True
                LblError.Text = ex.ToString()
                Session("FileUploadStatus") = "False"

            End Try
           
        End If

      

    End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Upload File</title>
    <style runat="server">
        .buttonStyleNew{
        border:2px solid #333333;
        font-size:12px;
        color:#FFFFFF;
        background-color:#656565;
        font-family:Arial, Helvetica, sans-serif;
        }
        .UploadNew{
        border:2px solid #333333;
        font-size:12px;
        color:#FFFFFF;
        font-family:Arial, Helvetica, sans-serif;
        }
    </style>
</head>
<body>
    <form id="FrmUpload" runat="server" method="post">
   <div>
<asp:FileUpload ID="filUpload" runat="server" CssClass="UploadNew" Width="364px" ForeColor="Black" />&nbsp;&nbsp;&nbsp;&nbsp;<asp:Button

ID="btnUpload" runat="server" Text="Upload File" CssClass="buttonStyleNew"/><br />&nbsp;<asp:Label runat="server" ID="LblError" Visible="False"

ForeColor="red" Font-Size="small" Font-Bold="false"></asp:Label><asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"

ErrorMessage="Only .doc , .docx, .xls, .xlsx, .pdf, .jpg or .txt files are allowed." ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w

[\w].*))+(.doc|.docx|.txt|.pdf|.xls|.xlsx|.ppt|.zip|.jpg|.png|.tiff|.PDF|.DOC|.DOCX|.JPG|.JPEG|.jpeg|.XLS|.XLSX|.PPT|.ZIP|.RAR|.rar|.TIFF)$"

ControlToValidate="filUpload"></asp:RegularExpressionValidator> </div>
    </form>
</body>
</html>
Report Abuse

Validating FileUpload control for specific file type and required field
by Haider M Rizvi 1/4/2012 3:43:07 AM

Hi Shoeb,

Try this:

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Only .doc , .docx or .txt files are allowed." ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.doc|.docx|.txt|.pdf|.xls|.xlsx|.ppt|.zip|.jpg|.png|.tiff|.PDF|.DOC|.DOCX|.JPG|.JPEG|.jpeg|.XLS|.XLSX|.PPT|.ZIP|.RAR|.rar|.TIFF)$" ControlToValidate="filUpload"></asp:RegularExpressionValidator>

 

Note: Remove spaces(if any) within ValidationExpression.

Report Abuse

Validating FileUpload control for specific file type and required field
by Shoeb Khan 1/4/2012 4:43:16 AM
still getting the same result

Report Abuse

Validating FileUpload control for specific file type and required field
by Haider M Rizvi 1/4/2012 5:22:04 AM
I am unable to reproduce the error. Here is the code which I am using in my HTML Body. Have a look.

Report Abuse

Validating FileUpload control for specific file type and required field
by Shoeb Khan 1/4/2012 5:38:08 AM
if you see my code, i have
      LblError.Visible = True
                    LblError.Text = "File physically Uploaded. Please remember to - confirm your attachment..."

which gets visible once's the file is successfully uploaded and i think this makes all the error visible at that time
Report Abuse

Validating FileUpload control for specific file type and required field
by Haider M Rizvi 1/4/2012 6:25:08 AM
Here is the code which I had written on click of Upload button.


Have a look at the above code.
Report Abuse
Title :
Comment :
Text ColorBackground Color
BoldItalicUnderline
LeftCenterRightJustify
Ordered ListBulleted List
IndentOutdent
Horizontal Rule
SubscriptSuperscript
HyperlinkImage
Design ModeDesign
View HtmlHtml
     
 
Latest Article by Haider M RizviRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Latest BlogsRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Top Viewed ArticlesRSS Feed
    
    
    
    
    
    
    
    
    
    
Top Viewed BlogsRSS Feed
    
    
    
    
    
    
    
    
    
    
Latest Interview QuestionsRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Total Online Users: 6833
Advertisement
MindStick DataConver
Advertise with Us
  
Copyright © 2009 - 2013MindStick. All Rights Reserved.