Click here to Skip to main content
15,881,850 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
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.

C#
//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;
 }

C#
//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
Updated 6-Sep-12 18:27pm
v2
Comments
sahabiswarup 7-Sep-12 0:49am    
good question!

try Below:
HTML
<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[^]
 
Share this answer
 
v2
Comments
Raj.Rautela 9-Sep-12 12:26pm    
thanks sir
prashant patil 4987 8-Jan-13 3:22am    
hey raj if this is your answer then you accep my solution..
hiii,



XML
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"...).
 
Share this answer
 
Comments
Raj.Rautela 9-Sep-12 12:27pm    
thanks sir
Ganesh Nikam 10-Sep-12 0:00am    
always welcome
Member 11030291 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 17-Dec-14 1:06am    
Yes it can work for .jpg extention as well, make sure that you have written correct validation Expression.
hi,

good morning,

apply below,

XML
--.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.
 
Share this answer
 
Comments
Raj.Rautela 9-Sep-12 12:27pm    
thanks sir..
prashant patil 4987 8-Jan-13 3:23am    
not sir called madam..
madhuri@mumbai 8-Jan-13 3:42am    
this is the effect of copy an paste...
prashant patil 4987 30-Oct-13 1:26am    
Yes Madhuri correct... :P LOLzzz
Hi,
Try the below code.

C#
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;
            }
        }
 
Share this answer
 
Comments
ganiganu 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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900