Question

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

Was it helpful?

Solution

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top