在输入字段中将字符限制为字母和数字 [英] Limit characters to Letters and Numbers in input field
问题描述
我希望尝试在我的网站上订阅的用户输入一个昵称,并且该昵称应仅由字母和数字组成(根本没有特殊字符).
I want that people trying to subscribe on my website to enter a nickname and that nickname should exclusively consist of letters and numbers (no special characters at all).
我想要的东西如下:仅abcdefghijklmnopqrstuvwxyz1234567890
.
I would like somthing as following : abcdefghijklmnopqrstuvwxyz1234567890
only.
如何检查它是否只有那些?
How can I check if it has only those?
推荐答案
HTML5解决方案将是...
The HTML5 solution would be...
<input type="text" id="input-nickname" name="nickname" pattern="[a-z\d]*" />
jsFiddle .
但是,为了获得最佳的浏览器支持,您可以使用JavaScript ...
However, for best browser support, you could use JavaScript...
document.getElementById('input-nickname').onkeyup = function(event) {
this.value = this.value.replace(/[^a-z\d]/, '');
}
jsFiddle .
要使JavaScript版本类似于HTML5方法,请查看表单的submit
事件.
To make the JavaScript version similar to the HTML5 method, look at the form's submit
event.
请记住,这对字母和数字有非常严格的定义.为了获得适当的Unicode支持,请找到您关心的范围,然后使用\u0000-\uFFFF
进行指定.
Keep in mind this has a pretty strict definition of letters and numbers. For proper Unicode support, find the ranges you care about and use \u0000-\uFFFF
to specify it.
这篇关于在输入字段中将字符限制为字母和数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!