any body tell me how can i restrict pasting and drop in asp.net?

Dani AI

Generated

Good starting points from (inline attributes) and (keyboard/mouse handlers). Both approaches can stop casual paste/drop attempts, but they are incomplete: client-side restrictions are easy to bypass (disabled JS, browser dev tools, automated scripts) and can break legitimate workflows (password managers, mobile keyboards, assistive tech). A more practical approach is to intercept paste/drop on the client, either block or sanitize the incoming text, and always enforce server-side validation/sanitization as the final gate.

A robust client-side handler that extracts plain text, cleans it, and inserts it at the caret is safer and gives control over what gets into the field. It also prevents pasted HTML from creating unexpected content. Example:

const tb = document.getElementById('TextBox1');

tb.addEventListener('paste', function(e) {
  const data = (e.clipboardData || window.clipboardData).getData('text');
  e.preventDefault(); // stop default paste
  const clean = data.replace(/<[^>]*>/g, '').replace(/\s+/g, ' ').slice(0, 500);
  const start = tb.selectionStart || 0;
  const end = tb.selectionEnd || 0;
  tb.value = tb.value.slice(0, start) + clean + tb.value.slice(end);
  const pos = start + clean.length;
  tb.setSelectionRange(pos, pos);
});

tb.addEventListener('drop', function(e) { e.preventDefault(); });
tb.addEventListener('dragover', function(e) { e.preventDefault(); });

Server-side sanitization is mandatory. In Web Forms code-behind, strip tags and normalize input before storing or using it:

protected void Save_Click(object sender, EventArgs e)
{
    var raw = TextBox1.Text ?? string.Empty;
    var cleaned = System.Text.RegularExpressions.Regex.Replace(raw, "<.*?>", string.Empty);
    cleaned = System.Web.HttpUtility.HtmlEncode(cleaned).Trim();
    // use 'cleaned' for storage/processing
}

Notes and trade-offs: consider beforeinput (modern browsers) to detect insertFromPaste earlier, but keep fallbacks. Prefer sanitizing over outright blocking except for very narrow fields (one-time codes). Always surface a clear message when paste/drop is prevented so legitimate users understand why an action failed.

Recommended Answers

All 2 Replies

try this code.
i hope this is useful for u.


<asp:TextBox ID="TextBox1" runat="server" onpaste="return false" onDrop="blur();return false" Width="438px" Height="36px"></asp:TextBox></div>

Hi..
You will need two java script functions for this:

function noCopyMouse(e) {
    var isRight = (e.button) ? (e.button == 2) : (e.which == 3);

    if(isRight) {
        alert('You are prompted to type this twice for a reason!');
        return false;
    }
    return true;
}

function noCopyKey(e) {
    var forbiddenKeys = new Array('c','x','v');
    var keyCode = (e.keyCode) ? e.keyCode : e.which;
    var isCtrl;

    if(window.event)
        isCtrl = e.ctrlKey
    else
        isCtrl = (window.Event) ? ((e.modifiers & Event.CTRL_MASK) == Event.CTRL_MASK) : false;

    if(isCtrl) {
        for(i = 0; i < forbiddenKeys.length; i++) {
            if(forbiddenKeys[i] == String.fromCharCode(keyCode).toLowerCase()) {
                alert('You are prompted to type this twice for a reason!');
                return false;
            }
        }
    }
    return true;
}

And a wee bit of code-behind to handle the two events for the textbox(es):

Textbox1.Attributes.Add("onmousedown", "return noCopyMouse(event);")
Textbox1.Attributes.Add("onkeydown", "return noCopyKey(event);")

Realize that the user can still use Edit|Copy and Edit|Paste in their browser menu. There's nothing you can do to prevent that, unfortunately.

Hope this helps! Don't forget to mark the most helpful post(s) as Answer for the sake of future readers. Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.