DIV CSS 佈局教程網

前端即時過濾非法字元
編輯:關於JavaScript     

表單要擋掉某些字元(例如 <>/@#% 或特定髒話),可以拆成兩個時機處理:按鍵當下攔截,以及內容變動後清理。

程式碼一:keypress 時使用

這個版本的思路是攔截按鍵,若字元落在黑名單裡就回傳 false 阻止輸入:

// 功能:過濾非法字元;說明:keypress 事件時使用
function surnam_keypress(event) {
var codes = '<>/@#%';              // 非法字元集
var e = event || window.event;
var code = e.charCode || e.keyCode;

if (e.charCode == 0) return true;    // 功能鍵直接放行
if (e.ctrlKey || e.altKey) return true;
if (code < 32) return true;          // ASCII 控制字元

var c = String.fromCharCode(code);   // 字元碼轉字元
if (codes.indexOf(c) != -1) {
return false;                        // 命中黑名單,不顯示
} else {
return true;
}
}

程式碼二:onchange/onkeyup 時使用

攔截按鍵擋不住貼上,所以要再補一層「事後清理」:

// 功能:過濾非法字元;說明:onchange、keyup 事件時使用
function surnam_keyup(text) {
var textvalue = text.value;
var codes = '<>/@#%';
var codearray = codes.split('');
for (i = 0; i < codearray.length; i++) {
while (textvalue.indexOf(codearray[i]) != -1) {
textvalue = textvalue.replace(codearray[i], '');
}
}
text.value = textvalue;   // 重新賦值
}

使用實例:在 ASP.NET 中統一掛上

/// <summary>
/// 為控制項加上字元過濾 js
/// </summary>
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);
}

兩個函式搭配使用的分工很清楚:keypress 負責讓使用者即時看到「這個字打不進去」的回饋,keyup/change 則負責把貼上等繞道寫入的内容清乾淨。

要强调的是,這一切都只是使用者體驗層級的防護。前端驗證永遠可以被繞過(停用 JavaScript、直接送 request),因此伺服器端一定要再驗證一次,這才是真正的安全防線。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved