如何通过javascript限制文本框中的特殊字符和空格? [英] How to restrict special characters and spaces in textbox via javascript?

查看:91
本文介绍了如何通过javascript限制文本框中的特殊字符和空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过javascript限制文本框中的特殊字符和空格?

How to restrict special characters and spaces in textbox via javascript?

推荐答案

试试这个



Try this

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script type="text/javascript">
        function blockSpecialChar(e) {
            var k = e.keyCode;
            return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8   || (k >= 48 && k <= 57));

        }

    </script>
</head>
<body>
    <form id="frm" runat="server">
      <input type="text" name="name"  onkeypress="return blockSpecialChar(event)"/>
    </form>
</body>
</html>


checkSpcialChar函数将限制输入框中的特殊字符。我们需要将事件作为该函数的参数传递。我们还更改了允许或禁止更多密钥的密钥代码。



checkSpcialChar function will restrict the special characters in the input box. We need to pass the event as a parameter for that function. We also change keycodes to allow or disallow more keys.

<html>
   <head>
      <script type="text/javascript">
         function checkSpcialChar(event){
            if(!((event.keyCode >= 65) && (event.keyCode <= 90) || (event.keyCode >= 97) && (event.keyCode <= 122) || (event.keyCode >= 48) && (event.keyCode <= 57))){
               event.returnValue = false;
               return;
            }
            event.returnValue = true;
         }
      </script>
   </head>
   <body>
      <form id="form1">
        <div>
            <input type="text" name="txtInput" id="txtInput" value="" onkeypress="return checkSpcialChar(event)">
        </div>
     </form>
   </body>
</html>



了解更多详情请参考此链接


function ValidateString(e){

var k;

document.all? k = e.keyCode:k = e.which;

return((k> 64 && k <91)||(k> 96 && k <123)|| k = = 8 || k == 32 ||(k> = 48 && k <= 57));

}
function ValidateString(e) {
var k;
document.all ? k = e.keyCode : k = e.which;
return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
}


这篇关于如何通过javascript限制文本框中的特殊字符和空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆