108

Is there a way using JavaScript to disable the ability to paste text into a text field on an HTML form?

E.g. I have a simple registration form where the user is required to input their email twice. The second email entry is to verify there are no typos in the first email entry. However if the user copy/pastes their email then that defeats the purpose and I've been experiencing users having problems because they've input the wrong email and copy/pasted it.

Maybe I wasn't clear on my question but I am not trying to prevent people from copying (or drag selecting) text on their browser. I just want to stop them from pasting input into a text field to minimize user error.

Perhaps instead of using this "hack" you can suggest another solution to the core problem of what I'm trying to solve here? I've done less than half a dozen user tests and this has already happened twice. My audience does not have a high level of computer proficiency.

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
justinl
  • 10,448
  • 21
  • 70
  • 88
  • 32
    Can't do much when it's a client insisting the change. enjoy your drink :) – justinl Jul 07 '11 at 04:05
  • 16
    It could be perfectly fine if he disables pasting in the verification field only when the email was NOT pasted into the original field. I other words, the user will either have to paste the email into both fields, or into neither field. – GJ. Nov 09 '12 at 21:42
  • 31
    If a client asks for this, tell them how bad an idea it is. It is a great way to piss off a client right at the point they are most likely to just walk away (at registration time). You do not want a customer relationship to start off with the customer being alienated. This practice is getting both increasingly common, and increasingly objectionable as more people use password managers. See also: http://ux.stackexchange.com/q/21062/9529 and ob. xkcd: http://xkcd.com/970/ – Mark Booth Dec 29 '14 at 13:12
  • I found this question while looking how to defeat this "feature" with element inspector. It worked! – SVD Nov 07 '17 at 21:59
  • 13 years later, websites are still doing this. I paste all kinds of things from my password manager, not just passwords. Show your client how to defeat this with a browser extension or by going into the developer console, then ask why they're trying to make life hard for their clients while adding no security to stop determined power users. – durette Oct 07 '22 at 14:10
  • @justinl You can simply not do it. Only a monster disables copy/pasting. – Philip Rego Oct 24 '22 at 15:11
  • I'd say is the other way around. If I copy paste my email (or 2FA code, or address, or whatever) then is more likely to be correct than typing. Especially now that the S key is missing from my keyboard and some keypresses are not recorded. Or when I'm on my phone with a a tiny touch keyboard. – user3285954 Jul 06 '23 at 22:17

25 Answers25

168

Don't do it. Don't mess with the user's browser. By Copy + Pasting into an E-Mail confirmation field, the user accepts responsibility over what they type. If they are dumb enough to copy + paste a faulty address (it has happened to me) then it's their own damn fault.

If you want to make sure that the E-Mail confirmation works out, have the user check their E-Mail while your site waits ("Please open your webmail program in a new window"). Show the E-Mail address in big fat letters ("The confirmation E-Mail was sent to.... made an error? CLick here to change).

Even better, if you can, let the user have some kind of limited access without confirming. That way, they can log in straight away and you improve your chances to keep in touch with the visitor even if the confirmation mail is blocked due to other reasons (e.g. spam filters).

Bala
  • 512
  • 9
  • 16
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • 7
    I agree with your answer for a scenario when the users are entering data themselves. However, when a user is entering an email address on behalf of someone else - for example, a CRM system or similar - it is not feasible to implement your solution. In these cases, the user is not their entering their own email address so they are likely to misspell it. If you allow pasting to the email confirmation box then you will get lots of incorrect data so there's nothing wrong with preventing the paste. As a developer you have to mitigate against "dumb enough" users to protect the business' data. – theyetiman Apr 24 '13 at 10:57
  • 25
    There is also the common case where the developer looking at this question has little or no control over the requirements of the project they are working on. This is not an answer to the question being asked here, so -1. – Nick Mar 09 '15 at 21:11
  • 9
    Saying don't do it doesn't answer the question. I currently have a requirement where the paste is to be disabled. – Darian Everett Sep 03 '15 at 16:14
  • 24
    if you're ever given a requirement like this it is your job as a professional to push back on it. you are more than a pair of hands who can write code. – Dan Jul 31 '16 at 02:54
  • 4
    This doesn't answer the question whatsoever. "How do I do XYZ?" "I recommend you don't do XYZ" –  Feb 27 '17 at 16:32
  • @JᴀʏMᴇᴇ so? "XYZ" is a bad idea. (Plus there's plenty of answers that *do* answer the question.) – Pekka Feb 27 '17 at 16:37
  • 2
    `so?` - well, quite simply, it's a forum for answering questions –  Feb 28 '17 at 09:21
  • @JᴀʏMᴇᴇ that seems like a pretty sad and simplistic view. If a practice is bad, it's worth pointing that out. The majority of learning I've done in this place has been because someone told me "ugh, don't do it that way". These days I'd probably do it in a comment, though... note the answer is seven years old. – Pekka Feb 28 '17 at 09:31
  • 9
    But there are valid reasons for almost anything and not answering someone's question because you don't think THEIR reason is valid is irritating. Let's say you had a quiz you were trying to implement with complex answers. Disabling paste and forcing the student to type the whole answer instead of copy pasting would make them commit the answer to memory whereas just a copy paste would probably be worthless. There is a valid reason to do this. Warn someone that what they are trying to do is not a good idea in most cases, but give an answer... or it's best to just not bother replying. – Halfhoot Aug 02 '17 at 19:39
  • I agree with this because I enjoy using my password managers and it requires pasting passwords, security answers, and pin numbers to be pasted in. I came to this page to find out how people block paste so I can help circumvent it using [an extension](https://github.com/jswanner/DontFuckWithPaste). – SomeGuyOnAComputer May 07 '18 at 19:15
  • 2
    There are scenarios where we must deny pasting info into a form field. Like when you ask the user to confirm an e-mail or password. – Marco Alves Sep 21 '18 at 19:05
  • 2
    Doesn't answer the question and assumes there are no good reasons to do it, which is wrong. – NateS Feb 04 '20 at 15:48
  • Be very careful that you're not disabling assistive technologies, putting yourself in violation of the Americans with Disabilities Act or the local equivalent in your jurisdiction. It's within the realm of professional responsibility to warn somebody in the field if they may be attempting something illegal. The technical answer is below but keeping developers out of the courts is valuable. – Bill McGonigle Apr 21 '22 at 22:11
  • I'm still very convinced that in in the grand scheme of things, this is the right answer. – Jaakko Mar 18 '23 at 15:41
  • @Nick, it might not answer your question, but it definitely does answer OP's question: 'Perhaps instead of using this "hack" you can suggest another solution to the core problem of what I'm trying to solve here?' – magras May 10 '23 at 08:22
77

Add a class of 'disablecopypaste' to the inputs you want to disable the copy paste functionality on and add this jQuery script

  $(document).ready(function () {
    $('input.disablecopypaste').bind('copy paste', function (e) {
       e.preventDefault();
    });
  });
Boycs
  • 5,610
  • 2
  • 28
  • 23
58

I recently had to begrudgingly disable pasting in a form element. To do so, I wrote a cross-browser* implementation of Internet Explorer's (and others') onpaste event handler. My solution had to be independent of any third-party JavaScript libraries.

Here's what I came up with. It doesn't completely disable pasting (the user can paste a single character at a time, for example), but it meets my needs and avoids having to deal with keyCodes, etc.

// Register onpaste on inputs and textareas in browsers that don't
// natively support it.
(function () {
    var onload = window.onload;

    window.onload = function () {
        if (typeof onload == "function") {
            onload.apply(this, arguments);
        }

        var fields = [];
        var inputs = document.getElementsByTagName("input");
        var textareas = document.getElementsByTagName("textarea");

        for (var i = 0; i < inputs.length; i++) {
            fields.push(inputs[i]);
        }

        for (var i = 0; i < textareas.length; i++) {
            fields.push(textareas[i]);
        }

        for (var i = 0; i < fields.length; i++) {
            var field = fields[i];

            if (typeof field.onpaste != "function" && !!field.getAttribute("onpaste")) {
                field.onpaste = eval("(function () { " + field.getAttribute("onpaste") + " })");
            }

            if (typeof field.onpaste == "function") {
                var oninput = field.oninput;

                field.oninput = function () {
                    if (typeof oninput == "function") {
                        oninput.apply(this, arguments);
                    }

                    if (typeof this.previousValue == "undefined") {
                        this.previousValue = this.value;
                    }

                    var pasted = (Math.abs(this.previousValue.length - this.value.length) > 1 && this.value != "");

                    if (pasted && !this.onpaste.apply(this, arguments)) {
                        this.value = this.previousValue;
                    }

                    this.previousValue = this.value;
                };

                if (field.addEventListener) {
                    field.addEventListener("input", field.oninput, false);
                } else if (field.attachEvent) {
                    field.attachEvent("oninput", field.oninput);
                }
            }
        }
    }
})();

To make use of this in order to disable pasting:

<input type="text" onpaste="return false;" />

* I know oninput isn't part of the W3C DOM spec, but all of the browsers I've tested this code with—Chrome 2, Safari 4, Firefox 3, Opera 10, IE6, IE7—support either oninput or onpaste. Out of all these browsers, only Opera doesn't support onpaste, but it does support oninput.

Note: This won't work on a console or other system that uses an on-screen keyboard (assuming the on-screen keyboard doesn't send keys to the browser when each key is selected). If it's possible your page/app could be used by someone with an on-screen keyboard and Opera (e.g.: Nintendo Wii, some mobile phones), don't use this script unless you've tested to make sure the on-screen keyboard sends keys to the browser after each key selection.

Christopher Parker
  • 4,541
  • 2
  • 28
  • 33
  • 71
    To prevent firefox to obey this stupid rule, go to about:config and change dom.event.clipboardevents.enabled to false – lolesque Apr 02 '14 at 13:38
  • 2
    even if I am not including the js you wrote, I am able to prevent user from pasting anything by just including `onpaste="return false"`, is there any issue if I go with that approach – viveksinghggits Jul 11 '16 at 12:25
  • @viveksinghggits The code implements `onpaste` in browsers which do not already provide it. You say "*I am able to prevent user from pasting anything*" but **which browsers did you test this in?** – AnnanFay Nov 09 '16 at 15:02
  • In regards to the implementation I see two obvious improvements: 1) only run the code in browsers where onpaste it not already supported, 2) re-execute when the DOM is modified - currently it will not be applied to dynamically added inputs. – AnnanFay Nov 09 '16 at 15:10
  • @Rick, so you're OK with textareas where users can paste anything into it? Becuz they will expect it to look exactly the same in other screens where the pasted data is displayed & they will expect it to look exactly the same when that data is inserted into an email. For me, I don't want the phone calls & support emails that will come with that. To disable pasting in a particular field is a viable option & question, IMHO. The problem most of us are having is when we use "Rich Text Editors" -- those things seem to override whatever javascript or jquery commands are present to prevent pasting. – McAuley Nov 11 '18 at 21:22
  • 1
    @McAuley So what? It's far, far worse to prevent paste, especially for something likely to be lengthy like a textarea. I likely wouldn't fill out that form at all if I needed to paste and couldn't. If I absolutely had to, the content would be terse and incomplete, and probably rude. You don't want to deal with a support call because formatting wasn't preserved? I doubt that happens very often, and it belies your laziness. Screw over a bunch of users to avoid some work. Nice. – Rick Nov 11 '18 at 21:25
35

Just got this, we can achieve it using onpaste:"return false", thanks to: http://sumtips.com/2011/11/prevent-copy-cut-paste-text-field.html

We have various other options available as listed below.

<input type="text" onselectstart="return false" onpaste="return false;" onCopy="return false" onCut="return false" onDrag="return false" onDrop="return false" autocomplete=off/><br>
Kailas
  • 7,350
  • 3
  • 47
  • 63
19

You can..... but don't.

You should not be altering the default behaviour of a users browser. It really is bad usability for your web application. Also if a user wants to disable this hack then they can just disable javascript on their browser.

Just add these attributes to the textbox

ondragstart=”return false” onselectstart=”return false”
Sheff
  • 3,474
  • 3
  • 33
  • 35
  • 7
    the question is about disabling pasting. this technique would only make copying difficult and not effect pasting at all. – bendman Jul 02 '13 at 17:51
9

Crazy idea: Require the user to send you an email as part of the signup process. This would obviously be inconvenient when clicking on a mailto link doesn't work (if they're using webmail, for example), but I see it as a way to simultaneously guarantee against typos and confirm the email address.

It would go like this: They fill out most of the form, entering their name, password, and whatnot. When they push submit, they're actually clicking a link to send mail to your server. You've already saved their other information, so the message just includes a token saying which account this is for.

Josh Lee
  • 171,072
  • 38
  • 269
  • 275
8

How about sending a confirmation email to the email address that the user has just entered twice in which there is a link to a confirmation URL on your site, then you know that they have got the message?

Anyone that doesn't click to confirm the receipt of the email may have entered their email address incorrectly.

Not a perfect solution, but just some ideas.

Richard Lucas
  • 630
  • 1
  • 4
  • 15
  • 4
    I have this implementation currently. The problem is that the user thinks they do not receive the email due to an error on our end because they check their email address that they *think* they entered and they do not have an email. Also what happens is that when they try to re-register again, the username that they used is now unavailable because it is stuck with that incorrect email address. – justinl Aug 04 '09 at 13:07
  • Tnen maybe add some workflow / code that runs everyday cleaning out usernames that have not been confirmed for say 2 days. – Colin Aug 04 '09 at 13:14
  • 1
    Thanks for the comment. My thoughts would be that if you tried to create an account on a website and it said that your user name was taken, would you go back again in 2 days and try it again? My thoughts are most likely not. Either you've created a new account with a different username the same day or you've not bothered coming back to the site because you couldn't figure out how to register and the site was "too complicated". – justinl Aug 04 '09 at 13:17
  • 8
    To continue what Colin is saying, you could possibly assume that when someone is trying to re-register with the same username and a different email address and they haven't responded to the confirmation message it's probably okay to let them do so. You might find that people get their domain correct in their email but misspell their username and could use this to further determine when someone has made a mistake? – Richard Lucas Aug 04 '09 at 13:18
  • 1
    I really like that idea of allowing users to re-register who have not yet confirmed their account information. I think this design solution is better than my original proposed technical solution. Hearing form everyone else that changing this default browser functionality was a bad idea was what I needed to hear to find a better solution. – justinl Aug 04 '09 at 14:47
7

You can use jquery

HTML file

<input id="email" name="email">

jquery code

$('#email').bind('copy paste', function (e) {
        e.preventDefault();
    });
Community
  • 1
  • 1
Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
5

Extending @boycs answer, I would recommend also using "on".

$('body').on('copy paste', 'input', function (e) { e.preventDefault(); });
Community
  • 1
  • 1
e3matheus
  • 2,112
  • 1
  • 20
  • 28
5

Functional approach with VanillaJS

function pasteNotAllowFunc(xid){
 let myInput = document.getElementById(xid);
     myInput.onpaste = (e) => e.preventDefault();
}

function copyNotAllowFunc(xid){
 let myInput = document.getElementById(xid);
     myInput.oncopy = (e) => e.preventDefault();
}


copyNotAllowFunc('copyInput')

pasteNotAllowFunc('pasteInput')
Copy
<input id="copyInput" value="copy not allow" />
<hr/>
Paste
<input id="pasteInput" value="paste not allow"/>
<hr/>
Textarea
<textarea id="test" value="Paste here"></textarea>
GMKHussain
  • 3,342
  • 1
  • 21
  • 19
3

Add a second step to your registration process. First page as usual, but on reload, display a second page and ask the email again. If it's that important, the user can handle it.

Alsciende
  • 26,583
  • 9
  • 51
  • 67
3

if you have to use 2 email fields and are concerned about the user incorrectly pasting the same mistyped email from field 1 to field 2 then i'd say show an alert (or something more subtle) if the user pastes something into the second email field

document.querySelector('input.email-confirm').onpaste = function(e) {
    alert('Are you sure the email you\'ve entered is correct?');
}

this way you don't disable paste, you just give them a friendly reminder to check what they've presumably typed in the first field and then pasted to the second field is correct.

shunryu111
  • 5,895
  • 4
  • 27
  • 16
2

Check validity of the MX record of the host of the given email. This can eliminate errors to the right of the @ sign.

You could do this with an AJAX call before submit and/or server side after the form is submitted.

max
  • 96,212
  • 14
  • 104
  • 165
1

You could attach a "keydown" listener to the input box to detect whether or not the Ctrl + V keys are being pressed and, if so, stop the event or set the input box's value to ''.

That wouldn't handle right clicking and pasting or pasting from the Edit menu of the browser, though. You may need to add a "last length" counter to the keydown listener and use an interval to check the field's current length to see if it increase since the last keystroke.

Neither is recommended, though. Form fields with paste disabled are extremely frustrating. I'm capable of typing my email correctly the first time, so I reserve the right to paste it into the second box.

Kevin
  • 3,771
  • 2
  • 31
  • 40
  • Not right click or even anything from Apples, Unix or ctrl-ins, and how about iPhones? – Martlark Aug 04 '09 at 10:09
  • I am also not a big fan of disabling the input field as I find that frustrating myself. But what are the other options to stop this type of user error? Or which solution will end up with the least incorrectly completed user registrations? It seems a bit annoying to have to type in an email address manually again, but if it's going to save frustrated potential customers then I'd prefer to force users to manually type something into an input field. I'm thinking it's not a big inconvenience and the amount of frustration it could save someone from a simple mistake might be worht it. Thoughts? – justinl Aug 04 '09 at 13:23
1

The way that I would resolve the issue of confirming an email address is as follows:

  1. Before going through the main process - say registering the user - first ask them to enter their email address.
  2. Generate a unique code and send it to that email address.
  3. If user has entered the correct email address, they will get the code.
  4. User must enter that code along with their email address, and their other required information, so they can complete the registration. - Please note that if this time they enter a wrong email address (or a wrong code), because it will not match with the code, the registration will not go through, and the user will be informed right away.
  5. If the email address, the code, and other registration information have been entered correctly, the registration is complete and user can start using the system immediately. - no need to to respond to any other email address in order to activate their account

For better security, the code should have a limited lifetime, and it should be allowed only once in the registration process. Also, in order to prevent any malicious robot applications, it is better to accompany the first step with captcha or a similar mechanism.

Majix
  • 570
  • 7
  • 14
1

I use this vanilla JS solution:

const element = document.getElementById('textfield')
element.addEventListener('paste', e =>  e.preventDefault())
Damjan Pavlica
  • 31,277
  • 10
  • 71
  • 76
1

from

Some may suggest using Javascript to capture the users' actions, like right-clicking the mouse or the Ctrl+C / Ctrl+V key combinations and then stopping the operation. But this is obviously not the best or simplest solution. The solution is integrated in the input field properties itself together with some event capturing using Javascript.

In order to disabled the browsers' autocomplete, simply add the attribute to the input field. It should look something like this:

<input type="text" autocomplete="off">

And if you want to deny Copy and Paste for that field, simply add the Javascript event capturing calls oncopy, onpaste, and oncut and make them return false, like so:

<input type="text" oncopy="return false;" onpaste="return false;" oncut="return false;">

The next step is using onselectstart to deny the input field's content selection from the user, but be warned: this only works for Internet Explorer. The rest of the above work great on all the major browsers: Internet Explorer, Mozilla Firefox, Apple Safari (on Windows OS, at least) and Google Chrome.

vaichidrewar
  • 9,251
  • 18
  • 72
  • 86
  • Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – Kev Sep 05 '11 at 22:20
  • yaah, I will take care next time onwards – vaichidrewar Sep 06 '11 at 14:18
  • 1
    Why not start now by describing what is "explained very nicely", that's how you get upvotes and better rep :) – Kev Sep 06 '11 at 14:21
  • What justification can there be for (trying to) turn autocomplete off? "We hate our users!" ? If you are trying to be the enemy of the user, they will hate you while they still will win in the end, because they control the browser. – Jan Hertsens Feb 19 '19 at 19:52
0

Using jquery, you can avoid copy paste and cut using this

$('.textboxClass').on('copy paste cut', function(e) {
    e.preventDefault();
});
Venkata Krishna
  • 14,926
  • 5
  • 42
  • 56
0

Simple solution: just reverse the registration process: instead of requiring confirmation at the end of registration process, request confirmation at the beginning of it! I.e. the registration process started with a simple form asking for e-mail address and nothing else. Upon submitting, an e-mail with link to a confirmation page unique to the e-mail address sent out. The user go to that page, then the rest of information for the registration (user name, full name, etc.) will be requested.

This is simple since the website does not even need to store anything before confirmation, the e-mail address can be encrypted with a key and attached as part of the confirmation page address.

0

With Jquery you can do this with one simple codeline.

HTML:

<input id="email" name="email">

Code:

$(email).on('paste', false);

JSfiddle: https://jsfiddle.net/ZjR9P/2/

Julius
  • 387
  • 6
  • 15
0

You can disable the copy paste option with jQuery by the below script:

jQuery("input").attr("onpaste","return false;");

of by using the bellow oppaste attribute into the input fields.

onpaste="return false;"
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
tapas talukder
  • 795
  • 6
  • 4
-1

what about using CSS on UIWebView? something like

<style type="text/css">
<!—-
    * {
        -webkit-user-select: none;
    }
-->
</style>

also you can read detail about block copy-paste using CSS http://rakaz.nl/2009/09/iphone-webapps-101-getting-safari-out-of-the-way.html

user275790
  • 291
  • 2
  • 3
-1

I did something similar to this for http://bookmarkchamp.com - there I wanted to detect when a user copied something into an HTML field. The implementation I came up with was to check the field constantly to see if at any time there was suddenly a whole lot of text in there.

In other words: if once milisecond ago there was no text, and now there are more than 5 chars... then the user probably pasted something in the field.

If you want to see this working in Bookmarkchamp (you need to be registered), paste a URL into the URL field (or drag and drop a URL in there).

Ivan Maeder
  • 321
  • 3
  • 11
-2
Hope below code will work :

<!--Disable Copy And Paste-->
<script language='JavaScript1.2'>
function disableselect(e){
return false
}
function reEnable(){
return true
}
document.onselectstart=new Function ("return false")
if (window.sidebar){
document.onmousedown=disableselect
document.onclick=reEnable
}
</script>
-2

if you are using angular

<input type="number" (keydown)="refuseInvalid($event) (input)="refuseInvalid($event)" (paste)="refuseInvalid($event)">           </input>

then in your javascript or typescript

refuseInvalid(event) {
    if (event.type == 'input' || event.type == 'paste') {
      event.preventDefault()
      return false;
    }
    if (["-", "+", "e", "."].includes(event.key)) {
      event.preventDefault();
      return false
    }
  }

Please note the use of ".". It will disallow decimal point numbers too.

davejoem
  • 4,902
  • 4
  • 22
  • 31