1

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)">
mplungjan
  • 169,008
  • 28
  • 173
  • 236
pixel
  • 9,653
  • 16
  • 82
  • 149

2 Answers2

1

References:

Character classes ([...]), Anchors (^ and $), Repetition (+, *)

The / are just delimiters, it denotes the start and the end of the regex. One use of this is now you can use modifiers on it.

function validatePaste(e) {
  var regex = /^[a-zA-Z]*$/;
  var copiedText = e.clipboardData.getData('text')
  if (!regex.test(copiedText)) {
    e.preventDefault(); //this line executes only if copiedText has all invalid characters
    return false;
  }
}
<input type="text" onpaste="validatePaste(event)">
Dipak
  • 2,248
  • 4
  • 22
  • 55
0

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)">
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • @mplungjan Thank you. Would you mind explaining why my regex was failing? Is it because I was missing the "+$" in it? What does "+$" mean? Thank you – pixel May 14 '21 at 17:32
  • 1
    ^=from start of field, $ till end. + means one or more. https://regex101.com/r/BhgmhN/1 – mplungjan May 14 '21 at 17:39
  • how is that different from using * instead of +? Thanks again – pixel May 14 '21 at 17:40
  • 1
    plus: one or more, * is 0 or more https://www.regular-expressions.info/repeat.html#:~:text=The%20asterisk%20or%20star%20tells,preceding%20token%20once%20or%20more.&text=The%20star%20repeats%20the%20second,second%20character%20class%20matches%20nothing. – mplungjan May 14 '21 at 17:43