Typical FileUpload RegularExpressionEvaluator Triggers Error, how to fix? - asp.net

On my page I have an standard asp:FileUpload control. Right below it is a RegularExpressionValidator that is supposed to only allow pdf and Word documents to be uploaded. It's the same regex seen all around the web. For some reason, it worked fine in aother project, but not in my current one. When loading the page in Firefox, I immediately get the validator to show me the error message right after selecting the file. This tells me it's a client side issue as the page has yet to be submitted to the server.
The tag:
<asp:RegularExpressionValidator id="Resume_Validator" runat="server"
ControlToValidate="Resume"
ValidationGroup="applicationForm"
ErrorMessage="Upload PDF or Word files only<br />"
Display="Dynamic"
CssClass="validationMsg"
ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.pdf|.PDF|.doc|.DOC|.docx|.DOCX)$"
/>

Why not just use jQuery file validation on the client-side?
//Check file extension
var ext = file.split('.').pop().toLowerCase(); //Check file extension if valid or expected
if ($.inArray(ext, ['txt']) == -1) {
$(".errorDiv").html("Select valid text file (txt).");
e.preventDefault(); //Prevent submission of form
}
else {
//Do your logic here, file upload, stream. etc.. if file was successfully validated
}

Related

changing the asp:Image ImageUrl attribute Depending on Condition in Asp.net

i'm building a simple reporting applications , in which user has notifications i want to check if the notification is unRead i'll display a read image icon
and if it was read , i'll display Read Icon
ive created a TicketIsUnRead() function to check if the ticket was read|unread
and i've used this code in aspx page that attaches different resource to the asp:image control different resources are responsible for changing the ImageUrl attribute
<asp:Image runat="server" id="ticketIcon" meta:resourcekey='<% (TicketIsUnRead(ticketNumberField.ToString()))? "UnReadticketIconResource" :"ReadticketIconResource"%>' />
and inside the Resx page
UnReadticketIconResource.ImageUrl images/UnReadMail.png
ReadticketIconResource.ImageUrl images/ReadMail.png
it seems that the Meta:resourcekey attribute doesn't allow the <% %> code
it returns parse error exception
Parser Error Message: '<% (TicketIsUnRead(ticketNumberField.ToString()))? "UnReadticketIconResource" :"ReadticketIconResource"%>' is not a valid resource key.

HTML File Upload in ASP.NET: HttpPostedFile Attributes Are Empty

In my ASP.NET web form, I'm trying to customize my File Upload panel. What I do is simply put an HTML input button and a textbox. And there's a hidden HTML file upload control. When user clicks on the button, file select window appears, when user selects the file, the value is written to the visible textbox.
It's all good so far. But I'm having a problem while trying to attach the selected file to email in code page.
Here's the HTML markup:
<asp:ImageButton ID="clickme" runat="server" ImageUrl="Images/browse.png" OnClientClick="$('#uploadme').click(); return false;" />
<input id="uploadme" name="uploadme" type="file" style="visibility: hidden;" onchange="CopyMe(this, 'txtFileName');" />
<input id="txtFileName" type="text" name="txtFileName" readonly="readonly" class="file-path" />
And the JS (I use this in order to copy the file name only and write it into txtFileName just to show to user):
<script type="text/javascript">
function CopyMe(oFileInput, sTargetID) {
var arrTemp = oFileInput.value.split('\\');
document.getElementById(sTargetID).value = arrTemp[arrTemp.length - 1];
}
And the CSS:
input[type=file] { width: 1px; }
I'm using the below code in my .cs file to get the file attributes:
HttpPostedFile file = Request.Files["uploadme"]
But I kept on getting null value. So after some research, I've learnt that my form has to use enctype="multipart/form-data" property. Since my .aspx file is under a master page file, I added this property to the form in my master page file. Now Request.Files["uploadme"] is not null but its file name is empty string and its ContentLength is 0.
I'm unable to understand what might be the source to this issue. If it's because of using Master Page's form, I can't add a form to my child page because it says a page can have only 1 form. I don't know if I could use JavaScript for uploading because I need to email the file after uploading so I don't know how to get the file after I upload via JS.
How can I solve this problem? It could be one way or another, all I need is a stylized upload panel and to e-mail file after uploading.
You're using a master page and I'm presuming that you are using .net 2.0 or greater. If that's the case, use a FileUpload control (you can still hide it using CSS). Using the FileUpload control means you won't need the enctype attribute (although you shouldn't generate any problems having it there).
This all being said, I don't believe to you copy values into file type fields and have documents upload. This would be a MAJOR security flaw as a website could potentially upload files from your machine without your knowledge.

IE9: Validation message not getting cleared

I am using an upload control which accepts only image files.If I select any non-image files I will be showing a validation error message "File type is invalid". The upload control i use is as follows
<UC:UploadControl runat="server" ID="file_logo" IsRequired="false" ReqValidationGroup="jpg" onkeypress="Javascript:CheckNumeric(event);" RequiredFieldMessage="Please upload Image file" CheckFileType="true" Width="870" Height="100" CheckDimension="false" RegexpFieldMessage="File type is invalid." FileFormats="gif,GIF,jpg,JPG,jpeg,JPEG" RegDisplay="true" />
I use another link to clear the error validation message. The code is
<a href='javascript:chkFileTypes("ctl00_mainContentPlaceHolder_file_logo_uploadfiles");clearInvalidLabel("ctl00_mainContentPlaceHolder_file_logo_uploadfiles")' >Clear File</a><br />
My Javascript function used to clear validation message is
function clearInvalidLabel(control) {
if (control == "ctl00_mainContentPlaceHolder_file_logo_uploadfiles") $("span[id$='file_logo_regexpType']").hide();
if (control == "ctl00_mainContentPlaceHolder_PopUp_logo_uploadfiles") $("span[id$='PopUp_logo_regexpType']").hide();}
Now if I again select an improper file using UploadControl, the error validation message is not getting displayed(Only in IE9). It works perfectly in other browsers. Please help me out.
Thanks.
Hard-coding IDs is easy to break. Try using the ClientID to access the control in JavaScript.
<a href='javascript:chkFileTypes("<%=UploadFilesControl.ClientID%>");clearInvalidLabel("<%=UploadFilesControl.ClientID%>")'>Clear File</a>
I would use the ClientID to get the validation labels too:
$("#<%=regexpType.ClientID%>").hide();

Creating a custom response with ASP.NET validation controls

I need to validate various ASP.NET controls, but instead of displaying the standard text/asterisk/image next to each when validation fails, I need to display custom content (change the outline color of the input textbox, display a tooltip, etc.). I could use a standard validation control in most cases (e.g., RequiredFieldValidator for a TextBox), except for the display when validation fails.
I've started out creating CustomValidators, but I need to do this many times for various validations (required field, regular expressions, ranges). It seems a waste to recreate the logic of these validators only so that it can change the response output. The MS documentation at http://msdn.microsoft.com/en-us/library/3w0bs977.aspx says a custom response can be done on both client and server in this case: "On both the client and server side you can create a custom response, such as a color change in a control or a font change for text on a label." It gives an example for the server side, but does not give a method for the client side. What is the best way to handle the custom response on the client?
This article might help you:
http://msdn.microsoft.com/en-us/library/aa479045.aspx
Particularly this section (look for "Client Side Validation" then under there, "Special Effects"):
<asp:Label id=lblZip runat=server
Text="Zip Code:"/>
<asp:TextBox id=txtZip runat=server
OnChange="txtZipOnChange();" /></asp:TextBox><br>
<asp:RegularExpressionValidator id=valZip runat=server
ControlToValidate=txtZip
ErrorMessage="Invalid Zip Code"
ValidationExpression="[0-9]{5}" /><br>
<script language=javascript>
function txtZipOnChange() {
// Do nothing if client validation is not active
if (typeof(Page_Validators) == "undefined") return;
// Change the color of the label
lblZip.style.color = valZip.isvalid ? "Black" : "Red";
}
</script>
There is still some wiring up that needs to be done, which you may be able to tidy up with some jQuery or the like

ASP.NET FileUpload: how to automatically post back once a file is selected?

I am working on a ASP.NET app and i have a need to post back to the server after a file is chosen in a FileUpload control without having to have the user explicitly click a 'submit' button. Is this possible? and if so, how?
I'm assuming you want to make the upload start right away. If so, you should react to the change event in JavaScript, and simply make it submit the form.
<!-- HTML code --->
<input
type="file"
onchange="if (confirm('Upload ' + this.value + '?')) this.form.submit();"
>
Asking the users for confirmation is recommendable, so they stay in control of the process and can cancel if they chose the wrong file by accident.
The first answer had the right javascript, but ASP.NET does not necessarily expose the input control directly, so it is better to put the onchange event on the FileUpload control.
<asp:FileUpload ID="myFileUpload" onchange="if (confirm('Upload ' + this.value + '?')) this.form.submit();" runat="server" />
Another route to go is to provide rich uploading via flash/silverlight/ajax. A great component for this can be found at Ajax Uploader for about $100

Resources