Disabling copy paste in a textbox on aspx page

Amit.jain
Posted by in JavaScript category on for Intermediate level | Views : 21194 red flag

For many reasons sometime we don't want to allow user to use right click to copy paste or by using ctrl+C , ctrl+v to copy and paste in textbox on a aspx page in asp.net
Introduction
We can use javascript to disable right mouse click or ctrl keys to ensure user is not able to copy paste in a textbox
we can achieve this in 2 ways

1. use this method when you don't want any alerts or message

<asp:TextBox ID="TextBox1" runat="server"
oncopy="return false"
onpaste="return false"
oncut="return false">
</asp:TextBox>
2. If you want to show alerts than use this method instead 
Right this javascript function in the head section of aspx page, in this function we are disabling right mouse click and ctrl keys
<head runat="server">
<title>Untitled Page</title>
<script language="javascript">
function DisableRightClick(event)
{
//For mouse right click
if (event.button==2)
{
alert("Right Clicking not allowed!");
}
}
function DisableCtrlKey(e)
{
var code = (document.all) ? event.keyCode:e.which;
var message = "Ctrl key functionality is disabled!";
// look for CTRL key press
if (parseInt(code)==17)
{
alert(message);
window.event.returnValue = false;
}
}
</script>
</head>
Now use this function on the textbox which we want to disable copy paste and right clicking
<body>
<form id="form1" runat="server">
<div>
<strong>
Right click disabled</strong> textbox
<br />
<asp:TextBox ID="TextBoxCopy" runat="server"
onMouseDown="DisableRightClick(event)">
</asp:TextBox><br />
<br />
<strong>Ctrl key </strong>disabled<br />
<asp:TextBox ID="TextBox2" runat="server"
onKeyDown="return DisableCtrlKey(event)">
</asp:TextBox><br />
<br />

Another method to disable<strong> Cut,Copy and paste
</strong>in textbox<br />
<br />
<asp:TextBox ID="TextBox1" runat="server"
oncopy="return false"
onpaste="return false"
oncut="return false">
</asp:TextBox>
</form>
</body>
Hope this helps 

Page copy protected against web site content infringement by Copyscape

About the Author

Amit.jain
Full Name: amiT jaiN
Member Level: Starter
Member Status: Member
Member Since: 12/26/2008 7:19:35 AM
Country:

http://csharpdotnetfreak.blogspot.com/

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)