文本框不允许输入特殊字符,只能是数字、字母、-和_,不允许输入空格键

在文本框的keypress事件调用下面函数。
如 <input disabled="disabled" type="text" id='userNameToEdit' onkeypress="TextValidate()" />

如果在文本框中按下特殊字符键,则显示警告信息,并且屏蔽输入。

function TextValidate()
{
    var code;
    var character;
    var err_msg = "Text can not contain SPACES or any of these special characters other than underscore (_) and hyphen (-).";
    if (document.all) //判断是否是IE浏览器
    {
        code = window.event.keyCode;
    }
    else
    {
        code = arguments.callee.caller.arguments[0].which;
    }
    var character = String.fromCharCode(code);
   
    var txt=new RegExp("[ ,\\`,\\~,\\!,\\@,\#,\\$,\\%,\\^,\\+,\\*,\\&,\\\\,\\/,\\?,\\|,\\:,\\.,\\<,\\>,\\{,\\},\\(,\\),\\',\\;,\\=,\"]");
    //特殊字符正则表达式
    if (txt.test(character))
    {
        alert("User Name can not contain SPACES or any of these special characters:\n , ` ~ ! @ # $ % ^ + & * \\ / ? | : . < > {} () [] \" ");
        if (document.all)
        {
            window.event.returnValue = false;
        }
        else
        {
            arguments.callee.caller.arguments[0].preventDefault();
        }
    }
}




评论: 1 | 引用: 0 | 查看次数: 5303
嗳妮不变[2010-07-23 03:47 PM | | | 124.227.247.248 | del | 取消审核 | 回复回复]
沙发
爱一人没那么容易
发表评论
昵 称:
密 码: 游客发言不需要密码.
邮 箱: 邮件地址支持Gravatar头像,邮箱地址不会公开.
网 址: 输入网址便于回访.
内 容:
验证码:
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 1000 字 | UBB代码 开启 | [img]标签 关闭