how to detect CTRL+C and CTRL+V key pressing using regular expression?

这一生的挚爱 提交于 2021-02-07 17:02:12

问题


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


回答1:


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




回答2:


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:

  • change
  • keyup
  • drop
  • paste
  • blur



回答3:


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);
});


来源:https://stackoverflow.com/questions/22092762/how-to-detect-ctrlc-and-ctrlv-key-pressing-using-regular-expression

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!