Click here to Skip to main content
11,480,938 members (63,242 online)
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#
sir,
I'm Developing an email application and m using a file upload control of asp.net i want to validate my file upload control for particular file type eg .pdf and .docx m using javascript code for validation but problem is that the alert fires properly but still it submits the wrong file..i want to stop wrong file submission using proper javascript. please help.

//1)
var id_value = document.getElementById("<%=FileUpload1.ClientID %>").value;
               if (id_value != '') {
                   var valid_extensions = /(.doc|.docx|.pdf)$/i;
                   if (valid_extensions.test(id_value)) {
                       alert('OK');
                   }
                   else {
                       alert('Invalid File')
 

                   }
               } 
               return true;
 }
//2)
System.Net.Mail.Attachment attachment;
            attachment = new System.Net.Mail.Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName);
            mail.Attachments.Add(attachment);
 
            string ext = System.IO.Path.GetExtension(FileUpload1.FileName);
            if (ext == ".doc" || ext == ".docx" || ext == ".pdf" || ext == ".DOC" || ext == ".DOCX" || ext == ".PDF")
            {
 
                smtpServer.Send(mail);
                
 

            }
            else
            {
                
                string Msg = "<script>alert('Please select .doc or .pdf files only');</script>";
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "alert", Msg, false);
                FileUpload1.Focus();
            }
these are the two code m using..
thanks in advance
Posted 6-Sep-12 19:07pm
Edited 6-Sep-12 19:27pm
v2
Comments
biswarup88 at 7-Sep-12 0:49am
   
good question!
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

try Below:
<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>
Restrict File Upload sample <br />
<asp:fileupload id="FileUpload1" runat="server" xmlns:asp="#unknown" />
<br />
<asp:button id="Button1" runat="server" text="Button" onclientclick="return validate();" xmlns:asp="#unknown" />
<br />
<asp:label id="Label1" runat="server" forecolor="Red" xmlns:asp="#unknown"></asp:label>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

refer Below Link. it will help you:
Link 1[^]
  Permalink  
v2
Comments
raj rautela at 9-Sep-12 12:26pm
   
thanks sir
prashant patil 4987 at 8-Jan-13 3:22am
   
hey raj if this is your answer then you accep my solution..
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

hiii,



Validating with RegularExpression validator:
 
<asp:FileUpload ID="UploadFile" runat="server" />
 
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Only Doc files are allowed"
 
ControlToValidate="UploadFile" ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.doc|.DOC)$">
 
</asp:RegularExpressionValidator>
 
In this example,  checked  ".doc" file type but you can use this example for any file type. Just replace ".doc" with file type you would  like to check( "Xml", "wmv"...).
  Permalink  
Comments
raj rautela at 9-Sep-12 12:27pm
   
thanks sir
Ganesh Nikam at 10-Sep-12 0:00am
   
always welcome
Member 11030291 at 16-Oct-14 9:51am
   
I tried this. But though I select correct format, it is still showing the error message. I tried it for ".jpg" format. Doesn't it works for this format?
Ganesh Nikam at 17-Dec-14 1:06am
   
Yes it can work for .jpg extention as well, make sure that you have written correct validation Expression.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

hi,

good morning,

apply below,

--.aspx page
<asp:FileUpload ID="FileUploadCtrl" runat="server"  Width="90%"/>
<asp:CustomValidator ID="CustomValidator2" runat="server" Display="Dynamic" ControlToValidate="FileUploadCtrl"
ErrorMessage="Please upload only pdf or docx file" SetFocusOnError="True" ValidateEmptyText="True"
ValidationGroup="ValGrp1" ClientValidationFunction="CheckValidFile"></asp:CustomValidator>
 
-- javascript
 
 function CheckValidFile(source, arguments) {
 
            var UploadDoc = document.getElementById('<%= FileUploadCtrl.ClientID %>');
            var myfile = UploadDoc.value;
            var format = new Array();
            var Extension = myfile.substring(myfile.lastIndexOf('.') + 1).toLowerCase();
            if (Extension == "pdf" || Extension == "docx") {
                arguments.IsValid = true;
            }
            else {
                if (UploadDoc.value == '')
                    alert('Please browse document to upload.');
                else
                    alert('Please upload only pdf or docx file.');
                arguments.IsValid = false;
            }
        }


used above customvalidator on your file upload control,and apply above javascript

hope this will help you.
  Permalink  
Comments
raj rautela at 9-Sep-12 12:27pm
   
thanks sir..
prashant patil 4987 at 8-Jan-13 3:23am
   
not sir called madam..
Madhuri Patil at 8-Jan-13 3:42am
   
this is the effect of copy an paste...
prashant patil 4987 at 30-Oct-13 1:26am
   
Yes Madhuri correct... :P LOLzzz
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

Hi,
Try the below code.

function validateFile() {
                var flag = 0;
                var uploadPath = document.getElementById('<%=FileUpload1.ClientID%>').value;
 
                if (uploadPath == "") {
                    alert('Please browse a file to upload');
                    return false;
 
                else {
                    if (uploadPath.indexOf('.') != -1) {
                        var validExtensions = new Array();
                        validExtensions[0] = 'doc';
                        validExtensions[1] = 'docx';
                        validExtensions[2] = 'pdf';
                        validExtensions[3] = 'msg';
 
                        var ext = uploadPath.substring(uploadPath.lastIndexOf('.') + 1).toLowerCase();
                        for (var i = 0; i < validExtensions.length; i++) {
                            if (ext == validExtensions[i]) {
                                flag = 1;
                                break;
                            }
                        }
 
                        if (flag == 0) {
                            alert('The type of file is not allowed');
                            return false;
                        }
                    }
                }
            }
            else {
                return false;
            }
        }
  Permalink  
Comments
ganiganu at 29-Jul-13 8:19am
   
how to validate file extension in fileupload control using javascript

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 294
1 OriginalGriff 145
2 CPallini 135
3 CHill60 130
4 Member 10254688 65
0 Sergey Alexandrovich Kryukov 8,184
1 OriginalGriff 7,701
2 Sascha Lefèvre 3,114
3 Maciej Los 2,491
4 Richard Deeming 2,335


Advertise | Privacy | Mobile
Web03 | 2.8.150520.1 | Last Updated 7 Sep 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100