Email 驗證
/**
* 驗證 Email 格式
* @param {string} email - 待驗證字串
* @returns {boolean} 格式是否正確
*/
function validateEmail(email) {
// RFC 5322 簡化版:本地部@域名
// 本地部:字母數字._%+- (不以點開頭/結尾/連續)
// 域名:標準域名格式
const 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])?)+$/;
return regex.test(email);
}
// 更簡單實用版 (覆蓋 99% 常見格式)
function validateEmailSimple(email) {
return /^[\w\-.]+@[\w-]+(\.[\w-]+)+$/.test(email);
}
// 使用範例
const emailInput = document.getElementById('email');
emailInput.addEventListener('blur', function() {
if (!validateEmail(this.value)) {
this.setCustomValidity('請輸入有效的 Email 格式');
this.reportValidity();
} else {
this.setCustomValidity('');
}
});
手機號碼驗證 (台灣為例)
/**
* 驗證台灣手機號碼
* 格式:09xxxxxxxx (10碼) 或 +8869xxxxxxxx
* @param {string} mobile
* @returns {boolean}
*/
function validateTaiwanMobile(mobile) {
// 移除所有非數字
const cleaned = mobile.replace(/\D/g, '');
// 09 開頭 10 碼
if (/^09\d{8}$/.test(cleaned)) return true;
// +886 9 開頭 9 碼 (去掉國碼 886)
if (/^8869\d{8}$/.test(cleaned)) return true;
return false;
}
/** 格式化顯示:0912-345-678 */
function formatTaiwanMobile(mobile) {
const cleaned = mobile.replace(/\D/g, '');
if (/^09\d{8}$/.test(cleaned)) {
return cleaned.replace(/(\d{4})(\d{3})(\d{3})/, '$1-$2-$3');
}
if (/^8869\d{8}$/.test(cleaned)) {
return '0' + cleaned.slice(3).replace(/(\d{4})(\d{3})(\d{3})/, '$1-$2-$3');
}
return mobile;
}
// 整合驗證與格式化
const mobileInput = document.getElementById('mobile');
mobileInput.addEventListener('blur', function() {
if (!validateTaiwanMobile(this.value)) {
this.setCustomValidity('請輸入有效的台灣手機號碼 (如 0912345678)');
} else {
this.setCustomValidity('');
this.value = formatTaiwanMobile(this.value); // 自動格式化
}
});
國際化手機號碼:推薦 libphonenumber
<script src="https://cdn.jsdelivr.net/npm/libphonenumber-js@1.10.0/bundle/libphonenumber-min.js"></script>
function validateMobileInternational(phone, countryCode = 'TW') {
try {
const phoneNumber = libphonenumber.parsePhoneNumberFromString(phone, countryCode);
return phoneNumber && phoneNumber.isValid();
} catch (e) {
return false;
}
}
function formatMobileInternational(phone, countryCode = 'TW') {
try {
const phoneNumber = libphonenumber.parsePhoneNumberFromString(phone, countryCode);
return phoneNumber ? phoneNumber.formatInternational() : phone;
} catch (e) {
return phone;
}
}
完整表單驗證整合範例
<form id="registerForm" novalidate>
<div class="field">
<label for="email">Email</label>
<input type="email" id="email" name="email" required autocomplete="email">
<span class="error-msg"></span>
</div>
<div class="field">
<label for="mobile">手機號碼</label>
<input type="tel" id="mobile" name="mobile" required autocomplete="tel" placeholder="0912345678">
<span class="error-msg"></span>
</div>
<button type="submit">註冊</button>
</form>
<script>
document.getElementById('registerForm').addEventListener('submit', function(e) {
e.preventDefault();
const email = this.email.value.trim();
const mobile = this.mobile.value.trim();
let valid = true;
// Email 驗證
if (!validateEmailSimple(email)) {
showError(this.email, 'Email 格式不正確');
valid = false;
} else {
clearError(this.email);
}
// 手機驗證
if (!validateTaiwanMobile(mobile)) {
showError(this.mobile, '手機格式錯誤,請輸入 09xxxxxxxx');
valid = false;
} else {
clearError(this.mobile);
this.mobile.value = formatTaiwanMobile(mobile);
}
if (valid) {
console.log('表單驗證通過,送出資料:', {email, mobile});
// this.submit(); 或 AJAX 送出
}
});
function showError(input, msg) {
input.classList.add('invalid');
input.nextElementSibling.textContent = msg;
}
function clearError(input) {
input.classList.remove('invalid');
input.nextElementSibling.textContent = '';
}
</script>
<style>
.field { margin-bottom: 15px; display: flex; flex-direction: column; gap: 5px; }
.field label { font-weight: 500; }
.field input { padding: 10px; border: 1px solid #ddd; border-radius: 4px; }
.field input.invalid { border-color: #e74c3c; }
.error-msg { color: #e74c3c; font-size: 13px; min-height: 18px; }
</style>
正則效能優化建議
- 預編譯正則:模組層級定義 `const EMAIL_RE = /.../;` 避免重複建立
- 避免災難性回溯:不使用嵌套量詞如 `(a+)+`,Email 正則已優化
- 輸入長度限制:`` (Email RFC 上限)
- 去抖動驗證:`input` 事件加 300ms debounce,減少即時驗證頻率
總結