nonstop328 nonstop328 - 7 days ago 7
Javascript Question

JQuery onpaste event to restrict user to paste characters like | , . /

I want to ensure that user can't paste string with (. | ") how do i prevent it? I was doing research about keyboard key and it work when user type. but how do i prevent paste?

here is jsfiddle Testing here

Here is my java script

$("[name='search']").on({
keydown: function(e) {
if (e.which === 32 || e.which === 220) {
e.preventDefault();
var v = this.value,
s = this.selectionStart;
this.value = v.substr(0, s) + '' + v.substr(s, v.length);
}
if (e.which === 55) {
e.preventDefault();
var v = this.value,
s = this.selectionStart;
this.value = v.substr(0, s) + '7' + v.substr(s, v.length);
}
},


// Here is the paste function but i no sure how to write it

paste: function(e) {
var s = this;
setTimeout(function() {
// here i no sure how to do it
});
}
});

Answer

You can use setTimeout along with bind as below and remove the characters using regular expressions.

$("[name='search']").on({
    keydown: function(e) {
        if (e.which === 32 || e.which === 220) {
            e.preventDefault();
            var v = this.value,
                s = this.selectionStart;
            this.value = v.substr(0, s) + '' + v.substr(s, v.length);
        }
         if (e.which === 55) {
            e.preventDefault();
            var v = this.value,
                s = this.selectionStart;
            this.value = v.substr(0, s) + '7' + v.substr(s, v.length);
        }
    },
    
    paste: function(e) {
        var stopPaste = function(){
           this.value = this.value.replace(/[|\s]/g, '');
        };
                        
        setTimeout(stopPaste.bind(this), 1);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><span>Search: </span><input type="text" name="search" size="75" /></div>

Comments