這裡分享一個以宣告式屬性驅動的表單驗證框架:在 input 上寫一個 validate 屬性,內容以分號分隔多條規則,框架遍歷表單時自動逐條執行,失敗就顯示提示並聚焦該欄位。
關鍵只有一行:把規則字串拼成程式碼後交給 eval 執行,回傳 false 就代表驗證未通過。
if (!eval(scriptCode)) { return false; }
<input type="text" class="text_field percentCheck"
name="progress_payment_two" id="progress_payment_two"
inputName="進度款2比例(%)"
validate="isNumeric;notNull"
maxLength="350" value="" />
validate 裡寫了兩條規則,框架會依序呼叫 isNumeric 與 notNull,任一失敗即回傳該規則定義的提示訊息。inputName 則是提示文字裡顯示的欄位名稱,未填寫時退回使用 name。
var ConfigValidateInfoType = "writeAlert"; // 可為 writeAlert、writePage,或 "writePage;writeAlert"
var rmTempStatusIsAlert = false; // 避免重複彈窗
var rmTempStatusIsFocus = false; // 避免重複聚焦
String.prototype.trim = function () {
return this.replace(/(^\s*)|(\s*$)/g, "");
};
// 驗證整個頁面上所有表單
function checkAllForms() {
var checkResult = true;
rmTempStatusIsAlert = false;
rmTempStatusIsFocus = false;
setAllVenusInputsDefault();
for (var i = 0; i < document.forms.length; i++) {
for (var j = 0; j < document.forms[i].elements.length; j++) {
var thisInput = document.forms[i].elements[j];
// 跳過 hidden、button、特殊 id,以及當下不可見的欄位
if (thisInput.type != "hidden" && thisInput.type != "button" &&
!(thisInput.id.indexOf("TF_") >= 0 && thisInput.id.indexOf("_TF") > 0) &&
thisInput.clientWidth != 0 && thisInput.style &&
thisInput.style.display != 'none') {
var rtValue = check(thisInput);
if (checkResult && rtValue == false) {
checkResult = false;
break;
}
}
}
}
return checkResult;
}
// 驗證單一欄位
function check(thisInput) {
var validateStr = thisInput.validate;
if (validateStr == null) return true;
var inputValue = thisInput.value;
var rules = validateStr.split(';');
for (var i = 0; i < rules.length; i++) {
if (rules[i].length == 0) continue;
s = replaceSingleQuote(inputValue);
try {
var scriptCode = "javascript:" + rules[i];
// 規則未自帶括號時,自動補上參數
if (rules[i].indexOf("(") < 0 || rules[i].indexOf(")") < 0) {
scriptCode = "javascript:" + rules[i] + "(s,thisInput)";
}
if (!eval(scriptCode)) return false;
} catch (e) {
alert("校驗函數" + rules[i] + "有異常,請檢查!\n" + e.message);
return false;
}
}
return true;
}
// 每輪驗證前先清除上一輪的錯誤樣式
function setAllVenusInputsDefault() {
for (var i = 0; i < document.forms.length; i++) {
for (var j = 0; j < document.forms[i].elements.length; j++) {
var frm = document.forms[i].elements[j];
if (frm.validate != null) {
setVenusInputDefault(frm);
writeValidateInfoAfterObject("", frm);
}
}
}
return true;
}
function setVenusInputDefault(_frm) {
_frm.style.borderStyle = "";
_frm.style.borderColor = "";
if (_frm.value != null) {
_frm.style.backgroundColor = "";
_frm.style.color = "";
}
}
// 特殊字元轉義,避免使用者輸入破壞 eval 的字串結構
function replaceSingleQuote(_str) {
var str = _str;
str = str.replace('\\', '\\u005C');
str = str.replace('\'', '\\u0027');
str = str.replace('(', '\\u0028');
str = str.replace(')', '\\u0029');
str = str.replace('\"', '\\u0022');
str = str.replace(';', '\\u0038');
return str;
}
// 錯誤提示:依設定決定用 alert 還是頁面內嵌文字
function writeValidateInfo(info, thisObj) {
var inputName = getInputNameFromObject(thisObj);
info = inputName + "的輸入有誤!\n" + info;
if (ConfigValidateInfoType.indexOf("writePage") >= 0) writeValidateInfoAfterObject(info, thisObj);
if (ConfigValidateInfoType.indexOf("writeAlert") >= 0) writeValidateInfoAlert(info, thisObj);
if (!rmTempStatusIsFocus) {
setVenusInputError(thisObj);
rmTempStatusIsFocus = true;
}
}
function setVenusInputError(_frm) {
try {
_frm.focus();
if (_frm.tagName != "SELECT") _frm.select(); // SELECT 不支援選取
_frm.style.borderStyle = "dashed";
_frm.style.borderColor = "rgb(255,50,0)";
if (_frm.value != null && _frm.value.length > 0) {
_frm.style.backgroundColor = "highlight";
_frm.style.color = "white";
}
} catch (e) { alert(e.message); }
}
function writeValidateInfoAlert(info, thisObj) {
if (!rmTempStatusIsAlert) { alert(info); rmTempStatusIsAlert = true; }
}
// 在欄位後方插入提示節點
function writeValidateInfoAfterObject(info, thisObj) {
var validateInfoObj = null;
thisObj = getValidatePosition(thisObj);
var next = thisObj.nextSibling;
if (next && next.nextSibling && next.tagName &&
next.tagName.toUpperCase() == "FONT" &&
next.nextSibling.tagName.toUpperCase() == "SPAN" &&
next.nextSibling.className == "font_remain_prompt") {
validateInfoObj = next.nextSibling;
} else {
thisObj.insertAdjacentHTML("afterEnd", "<font></font><span class=font_remain_prompt></span>");
validateInfoObj = thisObj.nextSibling.nextSibling;
}
if (validateInfoObj.innerHTML.length > 0 || info.length > 0) {
validateInfoObj.innerHTML = info;
}
}
function getInputNameFromObject(thisInput) {
var inputName = thisInput.inputName;
if (inputName == null || inputName.length == 0) {
inputName = thisInput.name;
if (inputName == null || inputName.length == 0) inputName = "";
}
return inputName;
}
// 全形字元算兩個長度
function getStrLength(str) {
var len = 0;
for (var i = 0; i < str.length; i++) {
if (str.charCodeAt(i) > 255) len += 2; else len++;
}
return len;
}
每條規則都是簽名一致的函式:接收字串值與欄位物件,通過回傳 true,否則呼叫 writeValidateInfo 後回傳 false。
function notNull(s, thisInput) { // 不可為空
try { thisInput.value = thisInput.value.trim(); } catch (e) {}
s = s.trim();
if (s.length == 0) { writeValidateInfo("不能為空或空格!", thisInput); return false; }
return true;
}
function isMobile(s, thisInput) { // 手機號碼
try { thisInput.value = thisInput.value.trim(); } catch (e) {}
s = s.trim();
if (s.length == 0) return true;
var prefixes = ["13", "14", "15", "18"], matched = 0;
if (s.length != 11) { writeValidateInfo('請輸入合法的手機號碼!', thisInput); return false; }
for (var i = 0; i < prefixes.length; i++) {
if (s.substring(0, 2) == prefixes[i]) matched++;
}
if (matched == 0) { writeValidateInfo('請輸入合法的手機號碼!', thisInput); return false; }
return true;
}
function isEmail(s, thisInput) { // Email
try { thisInput.value = thisInput.value.trim(); } catch (e) {}
s = s.trim();
if (s.length == 0) return true;
if (s.length > 100) { writeValidateInfo("email 地址長度不能超過 100 位!", thisInput); return false; }
var regu = /^(([0-9a-zA-Z]+)|([0-9a-zA-Z]+[_.0-9a-zA-Z-]*[0-9a-zA-Z]+))@([a-zA-Z0-9-]+[.])+([a-zA-Z]{2,})$/;
if (!regu.exec(s)) { writeValidateInfo("請輸入有效合法的 E-mail 地址!", thisInput); return false; }
return true;
}
function isNumeric(value, thisInput) { // 正整數或正小數
try { thisInput.value = thisInput.value.trim(); } catch (e) {}
value = value.trim();
if (value.length == 0) return true;
if (!/^\d+(\.\d+)?$/.test(value)) {
writeValidateInfo("請輸入正整數或者小數!", thisInput);
return false;
}
return true;
}
function checkIdCard(value, thisInput) { // 身分證(15 或 18 位)
try { thisInput.value = thisInput.value.trim(); } catch (e) {}
value = value.trim();
if (value.length == 0) return true;
if (!/^\d{15}(\d{2}[A-Za-z0-9])?$/.test(value)) {
writeValidateInfo("請輸入正確的身份證號碼!", thisInput);
return false;
}
return true;
}
function checkChinese(value, thisInput) { // 必須為中文
try { thisInput.value = thisInput.value.trim(); } catch (e) {}
value = value.trim();
if (value.length == 0) return true;
if (!/^[\u0391-\uFFE5]+$/.test(value)) {
writeValidateInfo("請輸入中文字符!", thisInput);
return false;
}
return true;
}
// 密碼強度:數字/大寫/小寫/特殊字元四類,每命中一類 +1,長度 ≥ 8 再 +1
function pwdStrength(pwd) {
var sum = [0, 0, 0];
for (var i = 0; i < pwd.length; i++) {
var c = pwd.charCodeAt(i);
if (c >= 48 && c <= 57) sum[0] = 1;
else if (c >= 65 && c <= 90) sum[1] = 1;
else if (c >= 97 && c <= 122) sum[1] = 1;
else sum[2] = 1;
}
var level = sum[0] + sum[1] + sum[2];
if (pwd.length >= 8) level++;
return level;
}
其餘規則(整數、浮點位數限制如 (18,2)、(20,6)、郵遞區號、電話、傳真、IP、金額、年份區間等)都沿用同一個簽名與結構,只是換掉正則與提示文字,這裡不再逐條列出。
這個框架的優點是擴充容易、接入成本低——新增一條規則只要寫一個函式,畫面上加一個屬性即可。但它的核心用 eval 拼字串執行,缺點也很明確:一是 replaceSingleQuote 那類字元轉義需要小心維護,任何遺漏都可能釀成程式碼注入;二是規則與提示寫在 HTML 屬性上,多語系與抽換訊息都不方便;三是無法處理跨欄位與跨表單的複雜約束。
如果是新專案,建議改用成熟的驗證函式庫,或把規則集中以設定檔描述、由框架查表呼叫,避免 eval。若維護的是既有系統,至少應把使用者輸入的轉義改為以 JSON.stringify 或參數化傳遞取代字串拼接。