JavaScript验证用户输入的是字符或数字
我们可以根据onkeydown事件的event.keyCode即是ASCII Chart来判断字符或数字等。相关键盘key对应的ASCII码:
参考下面JavaScript代码:
View Code
<script type = "text/javascript"> function isNumeric(keyCode) { return ((keyCode >= 48 && keyCode <= 57) || keyCode == 8) } </script> <script type = "text/javascript"> function isAlpha(keyCode) { return ((keyCode >= 65 && keyCode <= 90) || keyCode == 8) } </script> <script type = "text/javascript"> function isAlphaOrNumeric(keyCode) { return ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || keyCode == 8) } </script>
例子,用户只能输入字符和数字,并使用onpaste事件,不能粘贴。
<asp:TextBox ID="TextBox1" runat="server" onkeydown = "return isAlphaOrNumeric(event.keyCode);" onpaste = "return false;"></asp:TextBox>