萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 正則驗證手機、Email、郵遞區號:常用表單欄位驗證規則與即時回饋

常用驗證正則

1. 手機號碼(台灣/大陸通用簡化版)


// 台灣:09 開頭 10 碼
const TW_MOBILE = /^09\d{8}$/;

// 大陸:13-19 開頭 11 碼(含新號段)
const CN_MOBILE = /^1[3-9]\d{9}$/;

// 通用:支援 +886 / +86 前綴
const MOBILE = /^(?:\+?886|0)?9\d{8}$|^(?:\+?86)?1[3-9]\d{9}$/;

2. Email(RFC 5322 簡化版,實務足夠)


// 基本格式:local@domain.tld
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

// 較嚴格(常用)
const EMAIL_STRICT = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+$/;

⚠️ 完整 RFC 5322 正則極長,**不建議**直接用於前端。後端應用成熟庫驗證。

3. 郵遞區號(台灣 3+3 / 大陸 6 碼)


// 台灣:3 碼或 3+3 碼(不以 0 開頭)
const TW_ZIP = /^[1-9]\d{2}(?:-\d{3})?$/;

// 大陸:6 碼,首碼 1-9
const CN_ZIP = /^[1-9]\d{5}$/;

即時驗證元件封裝


class FieldValidator {
  constructor(inputEl, { regex, message, onValid, onInvalid }) {
    this.input = inputEl;
    this.regex = regex;
    this.message = message;
    this.onValid = onValid;
    this.onInvalid = onInvalid;
    this.bind();
  }

  bind() {
    this.input.addEventListener("input", () => this.validate());
    this.input.addEventListener("blur", () => this.validate(true));
  }

  validate(showMsg = false) {
    const val = this.input.value.trim();
    const ok = this.regex.test(val);
    this.input.classList.toggle("valid", ok && val);
    this.input.classList.toggle("invalid", !ok && val);
    if (showMsg) {
      this.input.setCustomValidity(ok ? "" : this.message);
      this.input.reportValidity();
    }
    if (ok) this.onValid?.(val); else this.onInvalid?.(val);
    return ok;
  }
}

// 使用
new FieldValidator(document.getElementById("mobile"), {
  regex: MOBILE,
  message: "手機格式錯誤(例:0912345678)",
  onValid: v => console.log("手機驗證通過", v),
  onInvalid: v => console.log("手機驗證失敗", v)
});

new FieldValidator(document.getElementById("email"), {
  regex: EMAIL_STRICT,
  message: "Email 格式錯誤"
});

new FieldValidator(document.getElementById("zip"), {
  regex: TW_ZIP,
  message: "郵遞區號 3 或 6 碼"
});

HTML 結構與樣式




進階:HTML5 內建驗證屬性






搭配 `

` 的 `novalidate` 由 JS 控制顯示時機,體驗最佳。

總結

  • 正則保持**簡單實用**,複雜規則交給後端/專用庫。
  • 封裝 `FieldValidator` 類別,統一處理即時驗證、視覺回饋、回調。
  • 善用 HTML5 `type`、`pattern`、`required` 降低 JS 負擔。
  • **前後端必雙重驗證**,前端為體驗,後端為安全。
copyright © 萬盛學電腦網 all rights reserved