傳統表單多在提交時驗證,但即時驗證能提升使用者體驗。核心作法是將 onchange 或 onblur 事件綁定到各欄位,讓輸入完成後立即檢查。

例如使用者名稱:
function checkuse(){
var username = document.getElementById("username").value;
if(username.length < 6 || username.length > 18){
alert("用戶名輸入不合法");
document.getElementById("username").focus();
return false;
}
return true;
}
提交時可串接所有驗證:
function check(){
return checkuse() && checkpwd() && checkpwdc() && checkemail();
}
表單的 onsubmit 若回傳 false,即可阻止送出。搭配 focus 與提示文字,能讓使用者快速修正錯誤。