在 Web 開發中,常遇到需限制輸入框不允許純空格,但使用者可能輸入「空格 + 文字」的情況。若直接存入資料庫,前導空格會佔用儲存空間,並可能影響查詢效能與資料一致性。
無論前端如何驗證,伺服器端務必再次清理資料,確保資料完整性。以 PHP 為例:
$clean = trim($_POST['input']); // 移除首尾空白
$clean = preg_replace('/\s+/', ' ', $clean); // 將多重空白合併為單一空格
使用 JavaScript 在提交前或輸入時過濾,提升使用者體驗:
// 提交前處理
document.getElementById('myForm').addEventListener('submit', function(e) {
const input = document.getElementById('a');
input.value = input.value.replace(/^\s+|\s+$/g, ''); // 去首尾空格
input.value = input.value.replace(/\s+/g, ' '); // 合併中間空格
});
// 或即時輸入過濾(僅允許非空格開頭)
document.getElementById('a').addEventListener('input', function() {
this.value = this.value.replace(/^\s+/, '');
});
資料庫中儲存含前導空格的字串,會導致:
採用「前端即時提示 + 提交前處理 + 伺服器端強制清理」三層防護,確保資料乾淨、效能最優。