Monday, January 2, 2012

how to validate file type in file upload control using JavaScript and diffrent type of regular expressions to validate file upload control in asp.net



Tuesday, December 14, 2010 
Introduction:

Here I will explain how to validate file type in file upload control using JavaScript.

Description:

I have one page that contains one file upload control to accept files from user and saving it in one folder. Here I need to give permission for user to upload only .doc or .docx files for that I have written validation by using JavaScript to validate files before save it in database.

Here I have some of regular expressions to validate file upload. 



Regular expression to validate file formats for .mp3 or .MP3 or .mpeg or .MPEG or m3u or M3U

Re= /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.mp3|.MP3|.mpeg|.MPEG|.m3u|.M3U)$/;

Regular expression to validate file formats for .doc or .docx

Re= /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.doc|.docx|.DOC|.DOCX)$/;

Regular expression to validate file formats for .txt or .TXT

Re= /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.txt|.TXT)$/;

Regular expression to validate file formats for .jpeg or .JPEG or .gif or .GIF or .png or .PNG

Re= /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpeg|.JPEG|.gif|.GIF| .png|.PNG)$/;


Here my requirement is to validate file for only .doc or .docx for that I have written following code in aspx page

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
<script type="text/javascript" language="javascript">
function validate() {
var uploadcontrol = document.getElementById('<%=FileUpload1.ClientID%>').value;
//Regular Expression for fileupload control.
var reg = /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.doc|.docx|.DOC|.DOCX)$/;
if (uploadcontrol.length > 0)
{
//Checks with the control value.
if (reg.test(uploadcontrol))
{
return true;
}
else
{
//If the condition not satisfied shows error message.
alert("Only .doc, docx files are allowed!");
return false;
}
}
//End of function validate.
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table align="center">
<tr>
<td>
<b>Restrict File Upload sample</b> <br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return validate();" />
<br />
<asp:Label ID="Label1" runat="server" ForeColor="Red"></asp:Label>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
 

 Demo

 
Other Related validation posts

No comments:

Post a Comment