無依賴、輕量的表單驗證思路:擴展 String.prototype 增加格式檢查,擴展表單元素增加驗證邏輯,最後統一調用。
// Email
String.prototype.isEmail = function() {
return /^[\w\-\.]+@[\w\-]+(\.[\w\-]+)+$/.test(this);
};
// URL
String.prototype.isUrl = function() {
return /^[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=?%\-&_~`@\[\]':+!]*([^<>""])*$/.test(this);
};
// 整數
String.prototype.isInteger = function() {
return /^[-+]?\d+$/.test(this);
};
String.prototype.isDateTime = function() {
return !isNaN(Date.parse(this));
};
Date.prototype.toIsoDate = function() {
const pad = n => n.toString().padStart(2,'0');
return `${this.getFullYear()}-${pad(this.getMonth()+1)}-${pad(this.getDate())} ${pad(this.getHours())}:${pad(this.getMinutes())}:${pad(this.getSeconds())}`;
};
HTMLInputElement.prototype.required = true; // 標記必填
HTMLInputElement.prototype.validate = function() {
const val = this.value.trim();
if (this.required && !val) return '此欄位必填';
if (this.type === 'email' && !val.isEmail()) return 'Email 格式錯誤';
if (this.dataset.type === 'url' && !val.isUrl()) return 'URL 格式錯誤';
return true;
};
<form id="form1">
<input type="email" name="email" required data-type="email" />
<input type="text" name="site" data-type="url" />
<button type="button" onclick="validateForm()">提交</button>
</form>
<script>
function validateForm() {
const inputs = document.querySelectorAll('#form1 input');
for (let el of inputs) {
const res = el.validate();
if (res !== true) { alert(res); el.focus(); return false; }
}
alert('驗證通過');
}
</script>
WeakMap 或獨立函式)、無異步驗證、錯誤訊息硬編碼。生產環境建議採用 validator.js、yup、vee-validate 等成熟庫。