简体   繁体   English

如何防止用户在复制粘贴操作时立即将带有无效字符的文本复制粘贴到输入文本字段中?

[英]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 az AZ characters) into my input field.我试图阻止用户将无效字符(除 az AZ 字符之外的任何字符)复制粘贴到我的输入字段中。 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.如果我复制包含所有无效字符(如“ 1234 ”)的粘贴文本,我的 if 块将被执行(正则表达式测试失败)并且工作正常。

However, it does not work if my copied text contains mix of valid or invalid characters (like ' 12abc ' or ' abc12 ').但是,如果我复制的文本包含有效或无效字符的混合(如“ 12abc ”或“ 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:我在输入文本元素上调用我的 javascript function,如下所示:

 function validatePaste(e) { var regex = /[az]/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)">

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 = /^[az]+$/gi; // gi makes AZ 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)">

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)">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM