表單校驗是每個前端都躲不掉的工作。下面這個範例不依賴任何框架,用原生 JavaScript 完成三件事:必填檢查、數值格式檢查,以及送出前的總體攔截。
· 第一欄為必填,在離開輸入框(blur)時檢查
· 第三欄只允許數字,在內容改變(change)時檢查
· 校驗失敗時,為該欄加上 aria-invalid 屬性並變更背景色,同時在頁面頂部產生一段 role="alert" 的提示
· 送出表單前統一掃描所有 aria-invalid="true" 的欄位,只要還有錯就阻止送出
用 aria 屬性來標記狀態,是個值得沿用的做法:它同時具備語意,對螢幕閱讀器等輔具也更友善。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>每天一個 JavaScript 實例 - 檢測表單資料</title>
<style>
[role="alert"]{ background-color: #fcc; font-weight: bold; padding:5px; border:1px dashed #000; }
div{ margin:10px 0; padding:5px; width:400px; background-color: #fff; }
</style>
<script>
window.onload = function(){
document.getElementById("thirdfield").onchange = validateField;
document.getElementById("firstfield").onblur = mandatoryField;
document.getElementById("testform").onsubmit = finalCheck;
}
// 第三欄:只允許數字
function validateField(){
removeAlert();
if(!isNaN(parseFloat(this.value))){
resetField(this);
}else{
badField(this);
generateAlert("第三欄只能填寫數字,例如 105 或 3.45");
}
}
// 移除舊的提示訊息
function removeAlert(){
var msg = document.getElementById("msg");
if(msg){
document.body.removeChild(msg);
}
}
// 復位:清除錯誤樣式與 aria-invalid
function resetField(elem){
elem.parentNode.setAttribute("style","background-color:#fff");
var valid = elem.getAttribute("aria-invalid");
if(valid) elem.removeAttribute("aria-invalid");
}
// 標記錯誤
function badField(elem){
elem.parentNode.setAttribute("style","background-color:#fee");
elem.setAttribute("aria-invalid","true");
}
// 產生提示區塊
function generateAlert(txt){
var txtNd = document.createTextNode(txt);
msg = document.createElement("div");
msg.setAttribute("role","alert");
msg.setAttribute("id","msg");
msg.setAttribute("class","alert");
msg.appendChild(txtNd);
document.body.appendChild(msg);
}
// 第一欄:必填
function mandatoryField(){
removeAlert();
if(this.value.length > 0 ){
resetField(this);
}else{
badField(this);
generateAlert("第一欄為必填");
}
}
// 送出前總檢查
function finalCheck(){
removeAlert();
var fields = document.querySelectorAll('input[aria-invalid="true"]');
console.log(fields);
if(fields.length > 0){
generateAlert("還有欄位填寫有誤,請修正後再送出");
return false;
}
}
</script>
</head>
<body>
<form id = "testform">
<div>
<label for="firstfield">*first Field:</label><br />
<input id="firstfield" name = "firstfield" type = "text" aria-required = "true" />
</div>
<div>
<label for="secondfield">Second Field:</label><br />
<input id="secondfield" name = "secondfield" type = "text" />
</div>
<div>
<label for="thirdfield">Third Field(numeric):</label><br />
<input id="thirdfield" name = "thirdfield" type = "text" />
</div>
<div>
<label for="fourthfield">Fourth Field:</label><br />
<input id="fourthfield" name = "fourthfield" type = "text" />
</div>
<input type="submit" value = "Send Data" />
</form>
</body>
</html>
· finalCheck 回傳 false 是阻止送出的關鍵,別忘了 return
· 選擇器要寫成 'input[aria-invalid="true"]',屬性值用雙引號,寫成單引號會選不到
· removeAlert() 每次都先清掉舊提示,避免訊息堆疊
· 若要擴充更多規則,只要沿用 badField/resetField 這兩個函數即可,樣式與狀態管理都已經抽離出來了