Home  >  Article  >  Web Front-end  >  网页前台通过js非法字符过滤代码(骂人的话等等)_javascript技巧

网页前台通过js非法字符过滤代码(骂人的话等等)_javascript技巧

WBOY
WBOYOriginal
2016-05-16 18:26:212284browse
代码一:keypress事件时使用
复制代码 代码如下:

/****************************************************/
//功能:过滤非法字符
//说明:keypress事件时使用
//作者:XXXXXXX
//日期:2010年5月7日
/****************************************************/
function surnam_keypress(event) {
//非法字符集
var codes = '/@#%';
//事件
var e = event || window.event
//打印字符码
var code = e.charCode || e.keyCode;
//功能按键时直接返回
if (e.charCode == 0) return true;
//ctr和alt直接返回
if (e.ctrlKey || e.altKey) return true;
//ASCII字符
if (code //字符码转为字符
var c = String.fromCharCode(code);
//如果有非法字符则不打印
if (codes.indexOf(c) != -1) {
return false;
}
else {
return true;
}
}

代码二onchage(主要是用户粘贴时处理用),keyup事件时
复制代码 代码如下:

/****************************************************/
//功能:过滤非法字符
//说明:onchange、keyup事件时使用
//作者:XXXXX
//日期:2010年5月7日
/****************************************************/
function surnam_keyup(text) {
//控件值
var textvalue = text.value;
//非法字符集
var codes = '/@#%';
//非法字符数组
var codearray = codes.split('');
//循环替换非法字符
for (i = 0; i while (textvalue.indexOf(codearray[i]) != -1) {
textvalue = textvalue.replace(codearray[i], '');
}
}
//重新给控件赋值
text.value = textvalue;
}

使用实例:
复制代码 代码如下:

///
/// 给控件添加字符过滤js
///

///
public void CharIllegalFilting(System.Web.UI.WebControls.TextBox text)
{
//控件内容改变
text.Attributes["onchange"] = "surnam_keyup(this);";
//键盘弹出事件
text.Attributes["onkeyup"] = "surnam_keyup(this);";
//键盘按下事件
text.Attributes["onkeypress"] = "return surnam_keypress();";
}
protected void Page_Load(object sender, EventArgs e)
{
//添加非法字符过滤
CharIllegalFilting(epNametext);
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn