javascriptonpaste

How to prevent user from copy-pasting text with invalid characters into input text field immediately on copy-paste action?


I have read few answers online and here on stack overflow but I am not finding a solution.

I am trying to prevent user from copy-pasting invalid characters (anything other than a-z A-Z characters) into my input field. I dont want to do this on submit but on copy-paste event.

If I copy paste text that has all invalid characters (like '1234'), my if block will get executed (regex test fails) and that works fine.

However, it does not work if my copied text contains mix of valid or invalid characters (like '12abc' or 'abc12').

How do I prevent user from copy-pasting text with invalid characters into my input text?

I am calling my javascript function on input text element like this:

function validatePaste(e) {
  var regex = /[a-z]/gi;
  var copiedText = e.clipboardData.getData('text')
  console.log(copiedText,regex.test(copiedText) )
  if (!regex.test(copiedText)) {
    e.preventDefault(); //this line executes only if copiedText has all invalid characters
    return false;
  }
}
<input type="text" onpaste="validatePaste(event)">


Solution

  • You only test there is one char there

    Here is a better regex - also we do not need to assign it every time

    const regex = /^[a-z]+$/gi; // gi makes A-Z irrelevant
    
    function validatePaste(e) {
      const copiedText = e.clipboardData.getData('text')
      console.log(copiedText, regex.test(copiedText))
      if (!regex.test(copiedText)) {
        e.preventDefault(); //this line executes if copiedText has any invalid characters
        return false;
      }
    }
    <input type="text" onpaste="validatePaste(event)">