Jquery:在按键上过滤输入 [英] Jquery: filter input on keypress
问题描述
我有一个文字字段,只接受以下字符:
I have a text field, which will accept only the following characters:
允许字符:[az 0-9 +# - 。]
当您提出问题时,这与标签字段中的 SO 过滤器相同。
如果用户键入无效字符,我希望当前文本字段值保持不变。我试过了:
This is the same filter SO does in the 'Tags' field, when you're asking a question. If the user types an invalid character, i want the current text field value to remain unchanged. I tried:
$('#post_tags').keypress(function(event){
var char = String.fromCharCode(event.which)
var txt = $(this).val()
if (! txt.match(/[^A-Za-z0-9+#-\.]/)){
$(this).val(txt.replace(char, ''));
}
})
为什么它不起作用?谢谢!
Why it doesn't work? Thanks!
推荐答案
/[^A-Za-z0-9+#-\.]/
这会否定任何一个字符的匹配。要使其匹配多个字符,您必须在其中使用 +
:
This negates the match of any one of those characters. To make it match more than one character, you have to use a +
in there:
/[^A-Za-z0-9+#-\.]+/
^
现在要匹配整个字符串,你需要添加锚点:
And now to match the whole string, you need to add anchors:
/^[^A-Za-z0-9+#-\.]+$/
^ ^
<编辑:好的,这里的 -
似乎也在创建一个从字符#
到<$ c的范围$ C> 。在这种情况下,您可以将其转义,或将其放在最后:
Okay, it seems that the -
here is also creating a range from character #
to .
. In this case, you can either escape it, or put it at the end:
/^[^A-Za-z0-9+#\-\.]+$/
/^[^A-Za-z0-9+#\.-]+$/
这篇关于Jquery:在按键上过滤输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!