如何禁止使用jQuery键入或粘贴字符(并替换字符)?
我正在尝试寻找一种方法来替换不允许的字符,使其不能以某种形式输入或粘贴到所有输入字段(本质上是文本框和文本区域)中.每当用户粘贴包含一个或多个不允许的字符的文本时,我都希望将字符替换为空字符串",但其余部分保持完整.如果他们键入并键入字符,我只会希望什么也不会发生"(例如,如果键入字符,字符就不会出现).
I’m trying to find a way to replace disallowed characters from being entered or pasted into all input fields (textboxes and textareas essentially) in a form. Any time a user pastes text that contains one or more disallowed characters I would want the character replaced with an empty string ‘’ but have the rest of the text intact. If they type and type the character I would just want "nothing" to happen (e.g. the character not to appear if they type it).
是否存在有关如何执行此操作的代码示例,或者已经执行此操作的jQuery插件(包含如何实际使用示例)?我正在尝试查找一种适用于任何形式的粘贴(从浏览器菜单,鼠标/菜单命令,粘贴的OS快捷方式等)以及通过键入直接用户输入的方法.
Is there a code sample that exists on how to do this or a jQuery plug-in that already does this (with an example of how to actually use it)? I’m trying to find a way that works for any form of paste (from a browser menu, with mouse / menu commands, OS shortcut for paste, etc.) as well as direct user input through typing.
具体来说,我们需要禁止使用{
,[
,]
或}
形式的括号.
Specifically we need to disallow braces in the form of {
, [
, ]
, or }
.
会是这样的:
HTML
<textarea name="" id="text" cols="30" rows="10"></textarea>
JS
$(function(){
$('#text').on('keyup paste',function(){
oldtxt = $(this).val();
find = '(\{?)(\}?)(\\[?)(\\]?)';
newtxt = oldtxt.replace(new RegExp(find, 'g'), '');
$(this).val(newtxt);
});
});