// 原文正則,問題:過度簡化、不支援子域名、不支援新頂級域、用 document.all 非標準
/^\w+((-\w+)|(\.\w+))*\@{1}\w+\.{1}\w{2,4}(\.{0,1}\w{2}){0,1}/ig
// 覆蓋 99%+ 真實場景,支援子域名、多級頂級域、特殊字符
const EMAIL_REGEX = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/;
<form>
<input type="email" name="email" required placeholder="請輸入郵箱">
<button type="submit">提交</button>
</form>
// 瀏覽器原生驗證,支援自定義提示:input.setCustomValidity('郵箱格式不正確')
/**
* 驗證郵箱格式
* @param {string} email - 待驗證郵箱
* @returns {boolean} 是否合法
*/
function isValidEmail(email) {
if (typeof email !== 'string') return false;
const trimmed = email.trim();
if (!trimmed) return false;
// 長度限制(RFC 5321: 本地部分 ≤64,域名 ≤255,總長 ≤254)
if (trimmed.length > 254) return false;
return EMAIL_REGEX.test(trimmed);
}
// 使用範例
const emailInput = document.getElementById('email');
const errorEl = document.getElementById('email-error');
emailInput.addEventListener('blur', () => {
const valid = isValidEmail(emailInput.value);
emailInput.classList.toggle('invalid', !valid);
errorEl.textContent = valid ? '' : '郵箱格式不正確,請重新輸入';
errorEl.hidden = valid;
});
// 表單提交攔截
document.getElementById('myForm').addEventListener('submit', (e) => {
if (!isValidEmail(emailInput.value)) {
e.preventDefault();
emailInput.focus();
}
});
前端無法直接查詢 DNS,需後端 API 輔助:
async function checkEmailDeliverable(email) {
const [, domain] = email.split('@');
try {
const res = await fetch(`/api/verify-email?domain=${encodeURIComponent(domain)}`);
const { hasMxRecord, isDisposable } = await res.json();
return { valid: hasMxRecord, warning: isDisposable ? '檢測到一次性郵箱' : null };
} catch { return { valid: true, warning: '無法驗證域名,跳過' }; }
}
| 誤區 | 正確做法 |
|---|---|
| 用極其複雜的正則追求 100% RFC 合規 | 正則無法完整實現 RFC 5322;採用「寬鬆驗證 + 發送驗證碼」雙重保障 |
| 只在前端驗證 | **後端必須再次驗證**,前端僅為 UX |
| 阻擋合法特殊字符(+、%、等) | Gmail 等大廠支援 `user+tag@gmail.com`,業務層面決定是否允許 |
| 用 `document.all` / `onChange` 內聯事件 | 用 `addEventListener`、模組化代碼、CSP 兼容 |