问题描述
我有一个文本框,它需要不允许用户输入任何特殊字符。他可以输入:
I have a textbox, and it needs not allow the user to enter any special characters. He can enter:
- A-Z
- A-Z
- 0-9
- 空间。
还有一个条件是第一个字母必须是字母。
我该怎么做一个JavaScript验证每个键preSS?
One more condition is the first letter should be alphabetic.How can I do a JavaScript verification on each keypress?
推荐答案
添加的onkeyup =JavaScript的:checkChar(本);到输入框。
add a onKeyUp="javascript:checkChar(this);" to the input box.
function checkChar(tBox) {
var curVal = tBox.value;
if ( /[^A-Za-z0-9 ]/.test(curVal) ) {
//do something because he fails input test.
}
}
alernatively检查恰好是pressed你可以从像这样的情况下抓住关键code的关键是:
alernatively to check JUST the key that was pressed you can grab the keycode from the event like so:
的onkeyup =JavaScript的:checkChar(事件);
onKeyUp="javascript:checkChar(event);"
function checkChar(e) {
var key;
if (e.keyCode) key = e.keyCode;
else if (e.which) key = e.which;
if (/[^A-Za-z0-9 ]/.test(String.fromCharCode(key))) {
//fails test
}
}
有关无缘第一个字符的一部分,但你可以做的文本框的值的测试作为第一个例子:
missed the part about first char, but you can do a test on the textbox value as in the first example:
/^[A-Za-z]/.test(curVal)
甚至用第二种方法,但传递的文本框,以及这样你就可以得到它的全部价值。
or even use the second method but pass the text box as well so you can get it's full value.
这篇关于文本框在JavaScript中的字母数字检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!