首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

JavaScript 表單驗證:即時顯示錯誤提示於輸入框後方完整實作

     編輯:程式設計疑難解答

需求

表單提交時驗證所有欄位,錯誤訊息動態插入至對應輸入框後方 (非 alert),支援用戶名、密碼、Email 格式驗證。

完整實作代碼

<form method="post" onsubmit="return checkBlank(this)">
    <input type="text" title="用戶名" placeholder="用戶名" /><br />
    <input type="password" title="密碼" placeholder="密碼" /><br />
    <input type="email" title="Email" placeholder="Email" /><br />
    <input type="submit" value="提交" />
</form>

<script>
// 顯示/移除錯誤標籤
function showMsg(input, msg) {
    const existingLabel = input.nextElementSibling;
    if (msg === false) {
        // 移除錯誤
        if (existingLabel && existingLabel.tagName === 'LABEL') {
            existingLabel.remove();
        }
    } else if (!existingLabel || existingLabel.tagName !== 'LABEL') {
        // 新增錯誤
        const label = document.createElement('label');
        label.style.color = 'red';
        label.style.marginLeft = '8px';
        label.textContent = msg;
        input.parentNode.insertBefore(label, input.nextSibling);
    } else {
        // 更新現有錯誤
        existingLabel.textContent = msg;
    }
}

// 空值檢查
function checkBlank(form) {
    for (let i = 0; i < form.length; i++) {
        const el = form.elements[i];
        if (el.type === 'submit') continue;
        
        if (el.value.trim() === '') {
            showMsg(el, el.title + ' 不能為空!');
            el.focus();
            return false;
        } else {
            showMsg(el, false); // 清除錯誤
        }
    }
    return true; // 允許提交
}

// 用戶名:3-20 位字母數字下劃線
function checkUsername(username) {
    return /^\w{3,20}$/.test(username);
}

// 密碼:字母開頭,6-20 位字母數字或 ._
function checkPWD(pwd) {
    return /^[A-Za-z][A-Za-z0-9._]{5,19}$/.test(pwd);
}

// Email 格式
function checkEmail(email) {
    return /^[\w.-]+@[\w.-]+\.\w+$/.test(email);
}

// 整合驗證 (可在 onblur 即時驗證)
function validateField(input) {
    const val = input.value.trim();
    let msg = false;
    switch (input.title) {
        case '用戶名': msg = checkUsername(val) ? false : '用戶名 3-20 位字母數字下劃線'; break;
        case '密碼': msg = checkPWD(val) ? false : '密碼以字母開頭,6-20 位字母數字或 ._'; break;
        case 'Email': msg = checkEmail(val) ? false : 'Email 格式不正確'; break;
    }
    showMsg(input, msg);
    return !msg;
}

// 綁定即時驗證
document.querySelectorAll('input[title]').forEach(input => {
    input.addEventListener('blur', () => validateField(input));
});
</script>

核心函數解析

函數職責關鍵技巧
showMsg動態插入/移除/更新錯誤標籤檢查 nextElementSibling 避免重複
checkBlank提交時空值檢查返回 false 阻止提交
validateField單欄位格式驗證可綁定 blur/input 事件

正則表達式詳解

/^\w{3,20}$/           // 用戶名:字母數字下劃線 3-20 位
/^[A-Za-z][A-Za-z0-9._]{5,19}$/  // 密碼:字母開頭,含字母數字._ 共 6-20 位
/^[\w.-]+@[\w.-]+\.\w+$/         // Email:簡易版,生產建議用更嚴格 RFC 5322 版本

進階:HTML5 原生驗證 (無 JS)

<form>
    <input type="text" required pattern="\w{3,20}" title="3-20 位字母數字下劃線" />
    <input type="password" required pattern="[A-Za-z][A-Za-z0-9._]{5,19}" title="字母開頭 6-20 位" />
    <input type="email" required />
    <input type="submit" />
</form>

// CSS 樣式化錯誤狀態
input:invalid { border-color: red; }
input:valid { border-color: green; }

避坑指南

  • ❌ alert() 阻塞 UI、體驗差 → ✅ 就地顯示錯誤
  • ❌ 驗證邏輯分散在各處 → ✅ 集中管理、復用函數
  • ❌ 僅前端驗證 → ✅ 後端必須再次驗證 (前端攔截誤觸,後端保安全)
  • ❌ 密碼欄位用 type="text" → ✅ type="password" 隱藏明文
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved