為減輕後端壓力、即時回饋使用者,前端提交前驗證是必要環節。本文整理三種主流綁定方式:jQuery bind submit、HTML onsubmit 屬性、原生 addEventListener,並提供完整可運行範例。
<form id="form1" action="/submit" method="post">
<input type="text" id="firstname" name="firstname" required>
<span id="firstnameLabel" class="error"></span>
<input type="text" id="lastname" name="lastname" required>
<span id="lastnameLabel" class="error"></span>
<button type="submit">提交</button>
<button type="button" id="btnReset">重置</button>
</form>
<script>
$(function() {
$("#form1").on("submit", function(e) {
const $form = $(this);
let valid = true;
// 清除舊錯誤
$form.find(".error").text("").hide();
// 驗證邏輯
$form.find("[required]").each(function() {
const $input = $(this);
const $label = $("#" + $input.attr("id") + "Label");
if (!$.trim($input.val())) {
$label.text($input.attr("placeholder") + " 不能為空").show();
valid = false;
}
});
if (!valid) {
e.preventDefault(); // 阻止提交
$form.find(".error:visible").first().prev("input").focus();
}
});
$("#btnReset").click(() => {
$("#form1")[0].reset();
$("#form1 .error").text("").hide();
});
});
</script>
<form id="form1" action="/submit" method="post" onsubmit="return checkForm(this)">
<input type="text" id="firstname" name="firstname">
<span id="firstnameLabel" class="error"></span>
<button type="submit">提交</button>
</form>
<script>
function checkForm(form) {
const firstname = $.trim(form.firstname.value);
const label = document.getElementById("firstnameLabel");
label.textContent = "";
if (!firstname) {
label.textContent = "名字不能為空";
label.style.color = "red";
form.firstname.focus();
return false; // 阻止提交
}
return true; // 允許提交
}
</script>
缺點:HTML 與 JS 耦合、難以維護、無法輕易綁定多個驗證器、CSP 限制內聯腳本。
<form id="form1" action="/submit" method="post">
<input type="email" id="email" name="email" required>
<span class="error" data-for="email"></span>
<button type="submit">送出</button>
</form>
<script>
document.getElementById("form1").addEventListener("submit", function(e) {
const form = this;
let valid = true;
form.querySelectorAll("[required]").forEach(input => {
const errorEl = form.querySelector(`[data-for="${input.id}"]`);
errorEl.textContent = "";
if (!input.checkValidity()) { // 使用原生 Constraint Validation API
errorEl.textContent = input.validationMessage;
errorEl.style.color = "red";
valid = false;
}
});
if (!valid) {
e.preventDefault();
form.querySelector("[required]:invalid").focus();
}
});
</script>
優點:無依賴、利用瀏覽器內建驗證(required、type="email"、pattern)、程式碼可攜性最高。
| 維度 | jQuery bind | HTML onsubmit | addEventListener |
|---|---|---|---|
| 依賴 | jQuery | 無 | 無 |
| 關注點分離 | 良好 | 差(內聯) | 良好 |
| 多驗證器組合 | 容易 | 困難 | 容易 |
| 原生驗證整合 | 需手動 | 需手動 | 原生支援 |
| CSP 相容 | 佳(外部檔) | 差(內聯) | 佳 |
| 推薦指數 | ★★★☆☆ (舊專案) | ★☆☆☆☆ | ★★★★★ (新專案) |
function validateForm(formEl, rules) {
// rules: { fieldName: { required: true, pattern: /regex/, message: "錯誤訊息" } }
let valid = true;
Object.keys(rules).forEach(name => {
const input = formEl.elements[name];
const rule = rules[name];
const errorEl = formEl.querySelector(`[data-for="${name}"]`);
if (rule.required && !input.value.trim()) {
showError(errorEl, rule.message || "必填");
valid = false;
} else if (rule.pattern && !rule.pattern.test(input.value)) {
showError(errorEl, rule.message || "格式錯誤");
valid = false;
}
});
return valid;
}
function showError(el, msg) {
if (el) { el.textContent = msg; el.style.color = "red"; }
}