表單失焦驗證(onblur)能即時反饋用戶輸入錯誤,提升體驗。本文提供原生JS完整示例:姓名非空、愛好非空驗證,並分析onblurvsonchange差異、現代Constraint Validation API、驗證狀態管理最佳實踐。
onblus→onblur)<script>
function validateOnBlur() {
var name = document.getElementById('name').value.trim();
var hobby = document.getElementById('hobby').value.trim();
var msg = '';
if (!name) msg = '請輸入您的名字!';
else if (!hobby) msg = '愛好不能為空!';
if (msg) {
alert(msg); // 或顯示在頁面提示區
return false;
}
return true;
}
</script>
<form name="frm" onsubmit="return validateOnBlur()">
<table>
<tr>
<td>您的姓名:</td>
<td><input type="text" id="name" onblur="validateOnBlur()" /></td>
</tr>
<tr>
<td>您的愛好:</td>
<td><input type="text" id="hobby" onblur="validateOnBlur()" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="提交"></td>
</tr>
</table>
</form>
| 事件 | 觸發時機 | 適用場景 |
|---|---|---|
onblur | 元素失去焦點 (點擊其他處、Tab鍵) | 即時單字段驗證、格式提示 |
onchange | 值改變並失去焦點 | select、checkbox、日期選擇器、內容實質變更才驗證 |
oninput | 值實時改變 (每次輸入) | 即時字數統計、格式化、防抖搜索 |
<form id="modernForm">
<input type="text" id="name" required minlength="2" maxlength="20"
placeholder="請輸入姓名" title "2-20位字符">
<input type="text" id="hobby" required pattern="\S+"
placeholder="請輸入愛好" title "不能為空">
<button type="submit">提交</button>
</form>
<style>
:invalid { border-color: #dc3545; }
:valid { border-color: #28a745; }
</style>
<script>
// 自定義提示樣式
document.getElementById('modernForm').addEventListener('invalid', function(e) {
e.preventDefault(); // 阻止默認氣泡
var el = e.target;
el.setCustomValidity(el.validationMessage); // 保留消息
showError(el, el.validationMessage);
}, true); // 捕獲階段攔截
function showError(el, msg) {
// 移除舊提示
var old = el.parentNode.querySelector('.error-msg');
if (old) old.remove();
// 插入新提示
var div = document.createElement('div');
div.className = 'error-msg';
div.style.color = 'red';
div.textContent = msg;
el.parentNode.appendChild(div);
}
// 清除錯誤
document.querySelectorAll('input').forEach(function(el) {
el.addEventListener('input', function() {
var msg = el.parentNode.querySelector('.error-msg');
if (msg) msg.remove();
});
});
</script>
validators: { name: [required, minLen(2)], email: [required, emailFormat] }fetch('/api/check') + setCustomValidityform.reportValidity() 或手動遍歷checkValidity()i18n體系const patterns = {
phone: /^1[3-9]\d{9}$/,
email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
idCard: /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/,
url: /^https?:\/\/.+/,
chinese: /^[\u4e00-\u9fa5]+$/,
password: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/
};