DIV CSS 佈局教程網

JavaScript 表單即時驗證的實作方式
編輯:關於JavaScript     

表單即時驗證

傳統表單多在提交時驗證,但即時驗證能提升使用者體驗。核心作法是將 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 與提示文字,能讓使用者快速修正錯誤。

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