在文本框的keypress事件调用下面函数。
如<inputdisabled="disabled"type="text"id='userNameToEdit'onkeypress="TextValidate()"/>
如果在文本框中按下特殊字符键,则显示警告信息,并且屏蔽输入。
functionTextValidate()
{
varcode;
varcharacter;
varerr_msg="TextcannotcontainSPACESoranyofthesespecialcharactersotherthanunderscore(_)andhyphen(-).";
if(document.all)//判断是否是IE浏览器
{
code=window.event.keyCode;
}
else
{
code=arguments.callee.caller.arguments[0].which;
}
varcharacter=String.fromCharCode(code);
vartxt=newRegExp("[,\\`,\\~,\\!,\\@,\#,\\$,\\%,\\^,\\+,\\*,\\&,\\\\,\\/,\\?,\\|,\\:,\\.,\\<,\\>,\\{,\\},\\(,\\),\\',\\;,\\=,\"]");
//特殊字符正则表达式
if(txt.test(character))
{
alert("UserNamecannotcontainSPACESoranyofthesespecialcharacters:\n,`~!@#$%^+&*\\/?|:.<>{}()[]\"");
if(document.all)
{
window.event.returnValue=false;
}
else
{
arguments.callee.caller.arguments[0].preventDefault();
}
}
}
如<inputdisabled="disabled"type="text"id='userNameToEdit'onkeypress="TextValidate()"/>
如果在文本框中按下特殊字符键,则显示警告信息,并且屏蔽输入。
functionTextValidate()
{
varcode;
varcharacter;
varerr_msg="TextcannotcontainSPACESoranyofthesespecialcharactersotherthanunderscore(_)andhyphen(-).";
if(document.all)//判断是否是IE浏览器
{
code=window.event.keyCode;
}
else
{
code=arguments.callee.caller.arguments[0].which;
}
varcharacter=String.fromCharCode(code);
vartxt=newRegExp("[,\\`,\\~,\\!,\\@,\#,\\$,\\%,\\^,\\+,\\*,\\&,\\\\,\\/,\\?,\\|,\\:,\\.,\\<,\\>,\\{,\\},\\(,\\),\\',\\;,\\=,\"]");
//特殊字符正则表达式
if(txt.test(character))
{
alert("UserNamecannotcontainSPACESoranyofthesespecialcharacters:\n,`~!@#$%^+&*\\/?|:.<>{}()[]\"");
if(document.all)
{
window.event.returnValue=false;
}
else
{
arguments.callee.caller.arguments[0].preventDefault();
}
}
}
本文介绍了一种在文本框中防止用户输入特定特殊字符的方法。通过使用JavaScript编写了一个名为TextValidate的函数,该函数能够在用户尝试输入指定的特殊字符时显示警告并阻止输入。
3344

被折叠的 条评论
为什么被折叠?



