5

I have an input field which I do not want users to paste any values in it. I am using the following jQuery code and it works fine on desktop Browser and iPhone Safari. The problem is it's not working on Android browser.

$('#no_paste').bind("paste", function(e) {                
        e.preventDefault();
});

Here's the fiddle

Paolo Stefan
  • 10,112
  • 5
  • 45
  • 64
CalebC
  • 922
  • 11
  • 24
  • I know it's not related to the question, but why disable paste? – Wesley Murch Aug 20 '13 at 04:47
  • Well, input fields like email-confirmation, password-confirmation are not supposed to be pasted. – CalebC Aug 20 '13 at 04:52
  • 1
    I'm not sure I agree with that. Some food for thought: [Preventing a user from pasting from the clipboard into a mandatory form field](http://ux.stackexchange.com/q/21062/4487), [Should I let a user copy/paste into a confirm e-mail field for a registration form?](http://ux.stackexchange.com/q/1488/4487) – Wesley Murch Aug 20 '13 at 05:11
  • This is really subjective and depends on the type of industry. It is undeniable that the lesser inputs would always be great on the user's perspective, in the end there's no fool's proof design as the system will only collect data with the right format and context is totally out of the question. – CalebC Aug 20 '13 at 05:33

1 Answers1

1

I've tested this on Galaxy SIII and Android browser doesn't seem to send the paste event. However, it still sends the input event after something was pasted.

If user is typing into a field he will fire one input event for each letter. However, if he is pasting, input event will fire only once for the whole string that was pasted. Basing on this observation we can block pasting like this:

$('#ie').bind("input", function() {
    var previousValue = $(this).data('old_value') || '',
        newValue = $(this).val();

    if((newValue.length - previousValue.length) > 1) {
        $(this).val(previousValue);
    }

    $(this).data('old_value', $(this).val());
});

You will find JSFiddle here.

Please note that this will also block autocomplete and all other strange input techniques that work in a similar fashion (I don't know about any).

Konrad Dzwinel
  • 36,825
  • 12
  • 98
  • 105
  • Good hack! But if the user pasting a single character it would still work. – CalebC Aug 21 '13 at 00:35
  • @CalebC Sure, but it's hard to believe that someone will paste whole email/password letter by letter only to avoid 'paste' protection. Doing so is much more complicated and cumbersome than typing, so what's the point? However, if your really have input fields where you expect only one letter then simply do that: if `input` event was sent but no `keydown` event was sent before it we can classify it as `paste`. – Konrad Dzwinel Aug 21 '13 at 07:32