DIV CSS 佈局教程網

JavaScript即時表單驗證:input與propertychange雙寫法
編輯:JavaScript基礎知識     

傳統表單驗證要等按下送出才知道填錯,體驗並不好。若能在輸入過程中就即時提示,使用者能立刻修正。做法是監聽輸入事件,邊打字邊驗證。

這裡有個相容性問題需要處理:現代瀏覽器用 oninput,而舊版 IE 只認 onpropertychange,因此兩個都掛上。

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>即時驗證</title>
<style>
#error {
    color: red;
    font-weight: bold;
}
</style>

<script type="text/javascript">
// Firefox、Chrome、Opera、Safari、IE9+
function OnInput(event) {
    var value = event.target.value;
    checkusername(value);
}

// 舊版 IE
function OnPropChanged(event) {
    if (event.propertyName.toLowerCase() == "value") {
        var value = event.srcElement.value;
        checkusername(value);
    }
}

// 驗證用戶名:只能是數字、字母與中文,不可含特殊字元
function checkusername(value) {
    var regex = /^[0-9a-zA-Z\u4e00-\u9fa5]*$/;

    if (regex.test(value) == true) {
        // 格式正確,清空提示
        document.getElementById("error").innerHTML = "";
    } else {
        // 格式錯誤,顯示提示
        document.getElementById("error").innerHTML =
            "用戶名格式錯誤,用戶名由數字、字母、中文組成,不能包含特殊字符";
    }
}
</script>
</head>

<body>
請輸入用戶名:
<input name="username" type="text"
    oninput="OnInput(event)"
    onpropertychange="OnPropChanged(event)"
    placeholder="數字、字母、漢字" />
<label id="error"></label>
</body>
</html>

幾個可以調整的細節

1. 正則的 * 與 +。這裡用 *,空字串也會通過。若希望「不可為空」,改成 + 或在驗證函數開頭加一個 if (!value) return; 的判斷。

2. 中文範圍。\u4e00-\u9fa5 只涵蓋基本漢字,不含擴充區與罕用字。一般表單夠用,若使用者可能輸入「㈱」這類符號就要另行處理。

3. 用 textContent 取代 innerHTML。提示訊息是純文字時,textContent 更安全也更高效,還能避免 XSS 風險。

4. 別忘了後端驗證。前端驗證只是為了改善使用者體驗,任何檢查都能被繞過,真正的把關永遠在伺服器端。

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