1

I've got a popup box which allows a user to type a brief (50 character) note. What I need to do is figure out how to prevent the user from copy/pasting a note using the right mouse click.

I looked up all the events available for a textbox, and onkeyup and onkeydown are not in this list but they do have an effect.

I have the following JavaScript that captures keystrokes:

<!--//**********************************
    // Comment Character Count
    //**********************************  -->
<script type="text/javascript">
     function textCounter(field, countfield, maxlimit) {
     if (field.value.length > maxlimit)
        field.value = field.value.substring(0, maxlimit);
     else
        countfield.value = maxlimit - field.value.length;
     }
 </script>

And then this textbox which calls the above function when a key is pressed:

<asp:TextBox ID="txtCommentBox" TextMode="MultiLine" CssClass="textbox" Wrap="True" 
Height="70px" Width="270px" Font-Size="Small" Rows="3" runat="server"  
onkeyup="textCounter(this, this.form.remLen, 50);" 
onkeydown="textCounter(this, this.form.remLen, 50);" />

Everything works awesome, except when someone right-clicks and chooses "Paste", it bypasses the check because no keys are pressed. Any ideas on how to trap for that? Is there an undocumented onmouseclick event I can call or something?

Johnny Bones
  • 8,271
  • 6
  • 39
  • 99
  • IIRC, I think there might be an `onpaste` event. Also, an `onchange` event that might be useful. I'm only working from memory, so I might be mistaken... – Michael McMullin Sep 25 '15 at 18:45
  • Please see: http://stackoverflow.com/questions/737022/how-do-i-disable-right-click-on-my-web-page – Drew Gaynor Sep 25 '15 at 19:20

2 Answers2

2

First, add an onpaste event to your TextBox:

<asp:TextBox ID="txtCommentBox" TextMode="MultiLine" CssClass="textbox" Wrap="True" 
Height="70px" Width="270px" Font-Size="Small" Rows="3" runat="server"  
onkeyup="textCounter(this, this.form.remLen, 50);" 
onkeydown="textCounter(this, this.form.remLen, 50);"
onpaste="textCounter(this, this.form.remLen, 50);" />

Next, adapt Fabrício Matté's solution to handle the timing difference between onpaste firing and value being populated:

function textCounter(field, countfield, maxlimit) {
    setTimeout(function () {
        if (field.value.length > maxlimit)
            field.value = field.value.substring(0, maxlimit);
        else
            countfield.value = maxlimit - field.value.length;

    }, 0);
}
Community
  • 1
  • 1
Michael McMullin
  • 1,302
  • 1
  • 10
  • 23
1

Use TextBox.MaxLength property. It'll prevent from adding additional characters even when pasting a text. You can also add asp.net custom validator to be sure the user hasn't changed you html in the browser editor.

<asp:TextBox ID="txtCommentBox" TextMode="MultiLine" CssClass="textbox" Wrap="True" 
Height="70px" Width="270px" Font-Size="Small" Rows="3" runat="server" MaxLength="50"/>