Disable pasting and typing of text in FileUpload Control
 
Author:
Filed Under: ASP.Net  |  JavaScript
Published Date: May 19, 2009
Views: 5181
 

Abstract: Here Mudassar Ahmed Khan has explained how prevent users from pasting or typing text in FileUpload control in ASP.Net using JavaScript

Comments:  1

 

In the ASP.Net FileUpload Control user can type in text also they can paste some text and click upload button which then causes an unnecessary server side call, hence many asked on forums on how to disable or prevent users from typing and pasting of text in the FileUpload Control. So here is the tip.

 

Consider the FileUpload Control below which does it for you

<asp:FileUpload ID="FileUpload1" runat="server"

                onkeydown = "return (event.keyCode==9);"

                onpaste = "return false;"  />

 

As you will notice I have added the following code on KeyDown event of FileUpload

onkeydown = "return (event.keyCode==9);"


The above JavaScript snippet checks if the key pressed is a Tab key (keyCode=9) and returns its result back to the KeyDown event. So whenever TAB key is pressed the conditions is satisfied and hence the TAB key works with the control if some other key other than TAB key is pressed then the condition is false hence it simply produces nothing

 

onpaste = "return false;"


This event is self explanatory disables pasting of any text inside the FileUpload Control.

 

When you add the two events to aspx page directly Visual Studio produces warning which is not an issue to worry since these are client side events and Visual Studio checks for Server Side events still if you do not want that to happen you can add the same from code behind too in the following way

 

C#

FileUpload1.Attributes.Add("onkeydown", "return (event.keyCode==9);");

FileUpload1.Attributes.Add("onpaste", "return false;");  

 

VB.Net

FileUpload2.Attributes.Add("onkeydown", "return (event.keyCode==9);")

FileUpload2.Attributes.Add("onpaste", "return false;")

 

This completes the article. You can download the sample code using the link below.

DisableTypingPastingFileUpload.zip (2.92 kb)









Related Articles



Comments



Add comments

You can add your comment about this article using the form below. Make sure you provide a valid email address
else you won't be notified when the author replies to your comment

Please note that all comments are moderated and will be deleted if they are
  • Not relavant to the article
  • Spam
  • Advertising campaigns or links to other sites
  • Abusive content.
Please do not post code, scripts or snippets.

Name*: Required
Email*: Required
Comment*: Required
Security code*: CaptchaInvalid Security Code
  Submit