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:

https://www.mindstick.com/Articles/176/fileupload-control-in-asp-dot-net

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:  https://www.mindstick.com/Articles/195/requiredfieldvalidator-control-in-asp-dot-net


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:


https://www.mindstick.com/Articles/197/regularexpressionvalidator-control-in-asp-dot-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.


  Modified On Nov-17-2017 09:06:32 PM
  1. 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>
  1. 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.

  1. 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>
  1. 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.

  1. 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>
  1. 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.

  1. 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

Leave Comment