表單前端驗證的入門範例:姓名非空檢查、Email 格式校驗 (包含 @ 符號檢測),通過 alert() 即時反饋,展示了早期表單交互的基本模式。
// 姓名非空驗證
function test1(form) {
if (form.text1.value == "") {
alert("您沒寫上任何東西,請再輸入一次 !");
} else {
alert("嗨 " + form.text1.value + "! 您已輸入完成 !");
}
}
// Email 格式驗證 (簡易版)
function test2(form) {
if (form.text2.value == "" || form.text2.value.indexOf('@', 0) == -1) {
alert("這不是正確的 e-mail address! 請再輸入一次 !");
} else {
alert("您已輸入完成 !");
}
}
<form name="first">
Enter your name:<br>
<input type="text" name="text1">
<input type="button" name="button1" value="輸入測試" onClick="test1(this.form)">
<p>
Enter your e-mail address:<br>
<input type="text" name="text2">
<input type="button" name="button2" value="輸入測試" onClick="test2(this.form)">
</form>
@,會通過 a@b、@domain.com 等非法格式alert() 會凍結主線程,體驗差,現代用內聯提示或 Toastrequired, type="email", pattern<form id="modern-form" novalidate>
<div>
<label for="name">姓名</label>
<input type="text" id="name" name="name" required
placeholder="請輸入姓名" aria-describedby="name-error">
<span id="name-error" class="error" aria-live="polite"></span>
</div>
<div>
<label for="email">Email</label>
<input type="email" id="email" name="email" required
placeholder="example@domain.com" aria-describedby="email-error">
<span id="email-error" class="error" aria-live="polite"></span>
</div>
<button type="submit">提交</button>
</form>
<script>
const form = document.getElementById('modern-form');
form.addEventListener('submit', e => {
if (!form.checkValidity()) {
e.preventDefault();
form.reportValidity(); // 瀏覽器原生 UI 提示
}
});
// 自定義錯誤訊息
document.getElementById('email').addEventListener('invalid', e => {
e.target.setCustomValidity('請輸入有效的 Email 地址,如 user@example.com');
});
</script>
const emailRegex = /^[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])?)+$/;
// 或使用 HTML5 原生 type="email" (瀏覽器內置較寬鬆驗證)