0

I have written this code in js to validate my text in an html input field. It works great except that I can't copy/paste anything into the textbox. How can I modify this to allow copy/pasting while not losing the validation functionality? Or is there a better way to validate a textbox?

function checkText(e)
{       
    var ok = /[a-z A-Z]/.test(String.fromCharCode(e.charCode));
    if (!ok)
        e.preventDefault();
}      
Barmar
  • 741,623
  • 53
  • 500
  • 612
user2236794
  • 441
  • 3
  • 7
  • 22

2 Answers2

0

As it's been mentioned in the comments, the paste event does not have the charcode property. You can try the following to handle both events:

function checkText(e)
{       
   var str = String.fromCharCode(e.charCode) || (event.clipboardData || window.clipboardData).getData('text')
   var ok = /[a-z A-Z]/.test(str);
   if (!ok)
     e.preventDefault();
}

So you handle both the keyboard and the paste events. The paste event will have to be only one char though.

David G.
  • 1,255
  • 9
  • 16
0

try it:

function checkInput(elem){
  let newValue = elem.value.split("").filter(chr => /[a-z A-Z]/.test(chr)).join("")
  elem.value = newValue;
}
<input onInput="checkInput(this);">
Bahador Raghibizadeh
  • 1,155
  • 11
  • 23