表單的 Email 欄位最好在輸入階段就給回饋,而不是等使用者按下送出才發現填錯。用 blur 事件搭配一個簡單的正則表達式就能做到。
<html>
<head>
<title>jquery 使用正則表達式驗證 email 地址</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(function () {
$(":input[name='email']").blur(function () {
var email = $(this).val();
var reg = /\w+[@]{1}\w+[.]\w+/;
if (reg.test(email)) {
$(":input[name='check']").val("email合法");
} else {
$(":input[name='check']").val("請輸入正確的email地址");
}
});
});
</script>
<style type="text/css">
h5 { color: blue; }
</style>
</head>
<body>
<h5>jquery 使用正則表達式驗證 email 地址</h5>
輸入Email地址:<input type="text" name="email" /><input type="text" name="check" style="border-width:0px;color:red" />
</body>
</html>
選擇器 :input[name='email'] 抓到輸入框,掛上 blur 事件——也就是「焦點離開時」才驗證。這樣使用者不會在打字打到一半就被紅字打斷。驗證結果寫入旁邊一個無邊框的 name="check" 欄位,作為提示文字顯示。
戒慎用 /\w+[@]{1}\w+[.]\w+/ 當作正式驗證規則,它會漏掉不少合法與非法的情況:
abcuser@domain.com 這種含 subdomain 的格式會失敗xxuser@domain.com.tw 只會比對到 .com 那段就通過@ 與 . 的位置與數量,a@b.c@d.e 也可能過關若只是做「粗淺提示」,夠用;若要真正把關,建議改用 HTML5 原生驗證:
<input type="email" name="email" required />
瀏覽器內建的 type="email" 會處理大部分格式判斷,並在無障礙輔具上表現更好。搭配 Constraint Validation API 的 checkValidity() 與 validity 物件,可以拿到比正則更細緻的錯誤原因。
無論用哪種方式,都只是使用者體驗層級的防護。真正的驗證一定要在伺服器端再做一次。