前端即時驗證手機號碼與 Email 格式,提升使用者體驗並減少後端無效請求。本文提供兩個可直接複製的驗證函式。
function checkSubmitEmail() {
var $email = $("#email");
if (!$email.val()) {
alert("郵箱不能為空!"); $email.focus(); return false;
}
// 簡易 RFC 5322 子集正則
if (!$email.val().match(/^\\w+((-\\w+)|(\\.\\w+))*@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$/)) {
alert("郵箱格式不正確"); $email.focus(); return false;
}
return true;
}
function checkSubmitMobil() {
var $mobile = $("#mobile");
if (!$mobile.val()) {
alert("手機號碼不能為空!"); $mobile.focus(); return false;
}
// 13x、159、153 開頭 + 8 位數字
if (!$mobile.val().match(/^(((13[0-9]{1})|159|153)+\\d{8})$/)) {
alert("手機號碼格式不正確!"); $mobile.focus(); return false;
}
return true;
}
/^1[3-9]\\d{9}$/ 通用 11 位驗證,或引入 libphonenumber 庫做嚴格校驗。type="email"、pattern 屬性,瀏覽器原生驗證可減少 JS 代碼。