萬盛學電腦網

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

JavaScript 手機號與電話號碼正則驗證大全(2024 最新號段支持)

中國大陸手機號規則 (2024)

  • 11 位數字,首位 1。
  • 第二位:3-9(已覆蓋所有運營商:移動、聯通、電信、廣電、虛擬運營商)。
  • 第三位:0-9(無限制)。
  • 剩餘 8 位:任意數字。

最簡通用正則:/^1[3-9]\d{9}$/

精確運營商/號段正則(可選)

// 僅驗證格式,不限制具體號段(推薦,號段頻繁變動)
const MOBILE_REGEX = /^1[3-9]\d{9}$/;

// 如需嚴格號段(需定期更新),示例:
const STRICT_MOBILE = /^(?:13[\d]|14[5-9]|15[0-35-9]|16[2567]|17[0-8]|18[\d]|19[0-35-9])\d{8}$/;
// 13x, 145-149, 150-153/155-159, 162/165-167, 170-178, 18x, 190-193/195-199

固定電話/座機驗證

// 格式:區號(3-4位)-號碼(7-8位)-分機(1-4位,可選)
// 區號可帶 0,也可不帶
const LANDLINE_REGEX = /^(?:0\d{2,3}-?)?\d{7,8}(?:-\d{1,4})?$/;
// 匹配示例:
// 010-12345678
// 021-87654321-123
// 12345678 (無區號)

統一驗證函數(推薦)


/**
 * 驗證手機/固話,自動識別類型
 * @param {string} val - 輸入字符串
 * @returns {{valid: boolean, type: 'mobile'|'landline'|'unknown', message: string}}
 */
function validatePhone(val) {
  if (!val || typeof val !== 'string') return { valid: false, type: 'unknown', message: '輸入不能為空' };
  const v = val.trim().replace(/[\s\-()()]/g, ''); // 移除常見分隔符

  if (/^1[3-9]\d{9}$/.test(v)) {
    return { valid: true, type: 'mobile', message: '' };
  }
  if (/^(?:0\d{2,3})?\d{7,8}(?:\d{1,4})?$/.test(v)) {
    return { valid: true, type: 'landline', message: '' };
  }
  return { valid: false, type: 'unknown', message: '格式不正確:手機號 11 位數字,座機含區號 7-8 位數字' };
}

// 使用
const r = validatePhone(' 138-0013-8000 ');
if (r.valid) console.log('手機號:', r.type);
else alert(r.message);

表單集成示例

<form id="contactForm">
  <input type="tel" id="phone" name="phone" placeholder="手機/座機" required 
         pattern="^(?:1[3-9]\d{9}|(?:0\d{2,3}-?)?\d{7,8}(?:-\d{1,4})?)$"
         title="請輸入正確的手機號或座機號">
  <span class="error-msg" aria-live="polite"></span>
  <button type="submit">提交</button>
</form>

<script>
document.getElementById('contactForm').addEventListener('submit', e => {
  const input = document.getElementById('phone');
  const r = validatePhone(input.value);
  if (!r.valid) {
    e.preventDefault();
    input.setCustomValidity(r.message);
    input.reportValidity();
    document.querySelector('.error-msg').textContent = r.message;
  } else {
    input.setCustomValidity('');
  }
});
</script>

國際電話號碼 (E.164)

若需支持國際號碼,強烈建議引入 libphonenumber-js(Google 官方庫),自動解析、驗證、格式化全球號碼。

import { parsePhoneNumberFromString } from 'libphonenumber-js';
const phone = parsePhoneNumberFromString('+86 138 0013 8000', 'CN');
if (phone && phone.isValid()) console.log(phone.formatInternational()); // +86 138 0013 8000

避坑指南

  • 不要寫死具體號段(如 13[0-9]、15[89]),運營商新號段頻繁釋放,維護成本極高。
  • 前端驗證**只能攔截誤輸**,**後端必須再次驗證**並標準化存儲(E.164 格式:+8613800138000)。
  • 輸入框 type="tel" 可喚起移動端數字鍵盤。
  • 允許用戶輸入空格、連字符、括號,驗證前統一清洗。
copyright © 萬盛學電腦網 all rights reserved