DIV CSS 佈局教程網

用 JS 與 jQuery 正則校驗郵箱、手機號與郵政編碼
編輯:關於JavaScript     

表單驗證是前端日常。下面把郵政編碼、手機號、電子郵箱三種常見欄位的校驗封裝成獨立函數,再用 jQuery 在輸入框失焦時即時提示。

jQuery 事件綁定部分

 $(function () {
  // 驗證郵政編碼
  $("#postcode").blur(function () {
    var postcode = $("#postcode").val();
    if (is_postcode(postcode)) {
      $("#postcode_info").html("");
    } else {
      $("#postcode_info").html("郵編格式不正確");
      return false;
    }
  });

  // 驗證手機號碼(先去除左右空白)
  $("#mobile").blur(function () {
    var mobile = $.trim($("#mobile").val());
    if (is_mobile(mobile)) {
      $("#mobile_info").html("");
    } else {
      $("#mobile_info").html("手機號格式不正確");
      return false;
    }
  });

  // 驗證 email
  $("#email").blur(function () {
    var email = $("#email").val();
    if (is_email(email)) {
      $("#email_info").html("");
    } else {
      $("#email_info").html("電子郵件格式不正確");
      return false;
    }
  });
});

校驗函數部分

 // 郵政編碼:6 位純數字
function is_postcode(postcode) {
  if (postcode == "") return false;
  return /^[0-9][0-9]{5}$/.test(postcode);
}

// 手機號:可選 +0/00 前綴,13x/14x/15x/18x 開頭共 11 位
function is_mobile(mobile) {
  if (mobile == "") return false;
  return /^0{0,1}(13[0-9]|15[0-9]|18[0-9]|14[0-9])[0-9]{8}$/.test(mobile);
}

// email:local@domain.tld 形式
function is_email(email) {
  if (email == "") return false;
  return /^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/.test(email);
}

幾點實務提醒:

· is_mobile 的號段規則會隨時間變化,寫死號段遲早要維護;若只是要「看起來像手機號」,用 ^1[3-9]\d{9}$ 更省心。
· email 正則做到 RFC 完整支援非常複雜,實務上不必追求完美,重点是攔掉明顯錯誤的輸入;真正的把關仍應放在後端。
· return false 在 blur 事件中並不會阻止任何預設行為,若要在提交時攔截表單,應該把校驗結果彙總到 submit 事件裡統一處理。
· 提示文字建議搭配 aria-live 屬性,讓螢幕閱讀器也能播報錯誤訊息。

把這三個函數抽成共用檔案,之後任何表單都能直接複用,不必每頁重寫一遍正則。

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