我正在使用 javascript 对项目进行一些表单验证。我所做的工作有效,但似乎可能有更好的方法来做到这一点。这是我所拥有的示例。
onkeypress="return keyNumOnly(event)"
function keyNumOnly(key)
{//this allows numbers and decimals.
var keychar;
var numcheck;
var keynum;
if(window.event) // IE
{
keynum = key.keyCode;
}
else if(key.which) // Netscape/Firefox/Opera
{
keynum = key.which;
}
if (keynum==8)
{
return true;
}
keychar = String.fromCharCode(keynum);
numcheck = /\d/;
if (keychar== ".")
{
return true;
}
return numcheck.test(keychar);
}
最佳答案
一些清理:
someTextbox.onkeypress = function(event) { // you can pass a function directly
var event = event || window.event,
// this means: event or window.event if event does not exist
keynum = event.keyCode || event.which,
// event.keyCode or event.which otherwise
keychar = String.fromCharCode(keynum),
numcheck = /\d/;
if(/\t|\./.test(keychar)) {
// checking for dot or tab using a regexp: \t is tab, | means 'or', \. is dot
return true;
}
return numcheck.test(keychar);
}
关于javascript - 使用 javascript 进行表单验证的 "right"方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6874053/