表單提交時驗證所有欄位,錯誤訊息動態插入至對應輸入框後方 (非 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 版本
<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" 隱藏明文