Validating FileUpload control for specific file types and required fields.
Here In this article, I am trying to explain how we can check and validate the user for uploading only certain files and making the uploading of a file to be a must for submission of a form.
For validating for the 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 a brief idea about the controls required.
Before starting about validating FileUpload we must have a brief idea about FileUpload control and Validation Controls of ASP.Net
FileUpload Control:
FileUpload control is used for uploading files to the server from the client-side.
For detailed reading about the 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 are:
"^(([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 the user will be forced to upload the file, this validation is only performed if the user tries to upload the file. If you want to make the 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.
Anonymous User
04-Jan-2012Have a look at the above code.
Shoeb Khan
04-Jan-2012LblError.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
Anonymous User
04-Jan-2012Shoeb Khan
04-Jan-2012Anonymous User
04-Jan-2012Hi Shoeb,
Try this:
<asp:RegularExpressionValidatorID="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.
Shoeb Khan
03-Jan-2012here 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" /> <asp:Button
ID="btnUpload" runat="server" Text="Upload File" CssClass="buttonStyleNew"/><br /> <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>
Anonymous User
03-Jan-2012I think you must have missed something.
Could you please post your latest code here.
Thanks,
Shoeb Khan
03-Jan-2012Anonymous User
29-Dec-2011You can ask you question in our forum section.
http://www.mindstick.com/mindForum/Topic.aspx
Shoeb Khan
29-Dec-2011Let me know if I can ask for a VB code for a calendar (not a dropdown calendar)
Anonymous User
29-Dec-2011All you need to do is to remove * from the validator.
Instead of validator below :
<asp:RegularExpressionValidatorID="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:RegularExpressionValidatorID="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.
Shoeb Khan
29-Dec-2011<%@ 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" /> <asp:Button ID="btnUpload" runat="server" Text="Upload File"
CssClass="buttonStyleNew"/><br /> <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>
Anonymous User
29-Dec-2011Hi 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:RegularExpressionValidatorID="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.
Shoeb Khan
28-Dec-2011In 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" /> <asp:Button ID="btnUpload" runat="server" Text="Upload File" CssClass="buttonStyleNew"/><br />
<asp:Label runat="server" ID="LblError" Visible="false" ForeColor="red" Font-Size="small" Font-Bold="false"></asp:Label></div>
</form>
</body>
</html>
John Smith
27-Mar-2011