萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

原生 JavaScript 表單驗證框架:擴展 String 與元素原型

無依賴、輕量的表單驗證思路:擴展 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 等成熟庫。

copyright © 萬盛學電腦網 all rights reserved