6

I have blocked all aTOz character input for my text field using regular expression in my JavaScript but as I have blocked entire alphabets I am not able to perform CTRL+C and CTRL+V, here is my regular expression goes:

var reValidChars = /[\x08\x0D\d]/;
iKeyCode = objEvent.charCode;
strKey = String.fromCharCode(iKeyCode); 
if (!reValidChars.test(strKey)) {
    return false;
}

Could you please help me in this issue. Thanks in advance

jezrael
  • 729,927
  • 78
  • 1,141
  • 1,090
preeth
  • 365
  • 3
  • 7
  • 19

3 Answers3

18

You can't detect key pressing with RegExp, though you can like following:

document.body.addEventListener("keydown",function(e){
    e = e || window.event;
    var key = e.which || e.keyCode; // keyCode detection
    var ctrl = e.ctrlKey ? e.ctrlKey : ((key === 17) ? true : false); // ctrl detection

    if ( key == 86 && ctrl ) {
        console.log("Ctrl + V Pressed !");
    } else if ( key == 67 && ctrl ) {
        console.log("Ctrl + C Pressed !");
    }

},false);

JSFiddle

nanobash
  • 5,293
  • 7
  • 34
  • 56
2

If you want to detect copying and pasting to your control you should use control events instead of regexp.

document.addEventListener('copy', function(e){
    e.clipboardData.setData('text/plain', 'Hello, world!');
    e.clipboardData.setData('text/html', '<b>Hello, world!</b>');
    e.preventDefault(); // We want to write our data to the clipboard, not data from any user selection
});

document.querySelector('textarea').addEventListener('paste', (e) => {
  console.log(e);
});
Jacek
  • 31
  • 2
0

Use the paste event to take an action upon pasting from the clipboard.

Note that users have many, many ways of getting content into your text boxes!

  • Typing
  • Autocomplete (doesn't fire key events in all browsers)
  • Paste via menu
  • Paste via keyboard shortcut
  • Drag & Drop highlighted text from other programs
  • Etc.

So instead of trapping things only on keyboard entry (keyup), you need to trap them at the actual paste level and other events too! This means you may also need to observe any or all of these events, depending on your situation:

DOOManiac
  • 5,846
  • 8
  • 44
  • 66