完整符合 RFC 5322 的 Email 正則超過 6000 字元,**不建議直接用於生產**。實務上採用「實用子集」平衡準確度與效能。
/^[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])?)+$/
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])?)+$/;
function validateEmail(email) {
if (typeof email !== 'string') return false;
if (email.length > 254) return false; // RFC 5321 最大長度
return EMAIL_REGEX.test(email.trim());
}
// 測試
console.log(validateEmail('user@example.com')); // true
console.log(validateEmail('user.name+tag@sub.domain.co.uk')); // true
console.log(validateEmail('user@[IPv6:2001:db8::1]')); // false (IP 字面格式需額外支援)
console.log(validateEmail('plainaddress')); // false
console.log(validateEmail('@missinglocal.com')); // false
function validateEmail(string $email): bool {
$email = trim($email);
if (strlen($email) > 254) return false;
$pattern = '/^[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 (bool)preg_match($pattern, $email);
}
<form>
<input type="email" name="email" required placeholder="name@example.com">
<button type="submit">送出</button>
</form>
瀏覽器自動驗證格式、顯示原生錯誤訊息、阻擋提交。**但僅做基本格式檢查,不保證郵箱真實存在。**