萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 限制輸入框僅允許數字與小數點完整實作

表單驗證中常需限制輸入框只接受數字或「數字+小數點」,本文提供生產級的 jQuery 解決方案,涵蓋即時過濾、貼上處理、輸入法禁用、行動裝置相容等完整面向。

核心實作程式碼

$(function() {
  // 僅允許整數 (含負號)
  $('.int-only').on('input paste', function(e) {
    var $this = $(this);
    var val = $this.val();
    
    // 過濾非數字、非負號字符
    var filtered = val.replace(/[^\d-]/g, '');
    // 確保負號只能出現在第一位
    if (filtered.indexOf('-') > 0) {
      filtered = filtered.replace(/-/g, '');
    }
    if (filtered.startsWith('-') && filtered.length > 1) {
      filtered = '-' + filtered.substring(1).replace(/-/g, '');
    }
    
    if (filtered !== val) {
      $this.val(filtered);
    }
  }).css('ime-mode', 'disabled'); // 禁用中文輸入法
  
  // 允許數字與單一小數點 (金額、價格等)
  $('.decimal-only').on('input paste', function(e) {
    var $this = $(this);
    var val = $this.val();
    
    // 過濾非數字、非小數點
    var filtered = val.replace(/[^\d.]/g, '');
    // 確保只有一個小數點
    var dotIndex = filtered.indexOf('.');
    if (dotIndex !== -1) {
      filtered = filtered.substring(0, dotIndex + 1) + 
                 filtered.substring(dotIndex + 1).replace(/\./g, '');
    }
    // 限制小數位數 (如最多 2 位)
    if (dotIndex !== -1 && filtered.length - dotIndex > 3) {
      filtered = filtered.substring(0, dotIndex + 3);
    }
    
    if (filtered !== val) {
      $this.val(filtered);
    }
  }).css('ime-mode', 'disabled');
  
  // 正整數 (不含 0 開頭)
  $('.positive-int').on('input paste', function() {
    var $this = $(this);
    var val = $this.val().replace(/[^\d]/g, '').replace(/^0+/, '');
    $this.val(val || '0'); // 空值時顯示 0
  }).css('ime-mode', 'disabled');
});

HTML 使用範例

<!-- 整數輸入 (可輸入負數) -->
<input type="text" class="form-control int-only" placeholder="整數,可負數" />

<!-- 金額輸入 (兩位小數) -->
<input type="text" class="form-control decimal-only" placeholder="金額,如 123.45" />

<!-- 正整數 (數量、編號) -->
<input type="text" class="form-control positive-int" placeholder="正整數" />

關鍵技術細節解析

技術點 說明
input 事件 取代舊版 keyup,可捕獲拖曳、自動填入、瀏覽器建議等所有值變更來源
paste 事件 處理 Ctrl+V、右鍵貼上、手機長按貼上等非鍵盤輸入
ime-mode: disabled CSS 禁用輸入法編輯器,防止中文拼音干擾 (IE/Edge/舊版 Chrome 有效)
正則邊界處理 負號定位、小數點唯一性、小數位數限制、前導零處理

行動裝置優化

// 強制數字鍵盤 (iOS/Android)
$('.decimal-only, .int-only, .positive-int').attr({
  'inputmode': 'decimal',     // 顯示數字鍵盤含小數點
  'pattern': '[0-9]*',        // 輔助 pattern 屬性
  'autocomplete': 'off'       // 避免瀏覽器自動填入干擾
});

// iOS Safari 補強:阻止非數字鍵
$('.decimal-only').on('keydown', function(e) {
  // 允許:數字鍵、小數點、Backspace、Tab、方向鍵、Delete、Home/End
  var allowed = [8, 9, 37, 39, 46, 36, 35, 110, 190]; // 鍵碼
  var isNumber = (e.keyCode >= 48 && e.keyCode <= 57) || // 主鍵盤數字
                 (e.keyCode >= 96 && e.keyCode <= 105);   // 小鍵盤數字
  
  if (!isNumber && allowed.indexOf(e.keyCode) === -1) {
    e.preventDefault();
  }
  
  // 防止多個小數點 (鍵盤層面攔截)
  if ((e.keyCode === 110 || e.keyCode === 190) && 
      $(this).val().indexOf('.') !== -1) {
    e.preventDefault();
  }
});

表單提交前最終驗證

function validateNumericInputs() {
  var isValid = true;
  var errorMsgs = [];
  
  $('.decimal-only').each(function() {
    var val = $(this).val().trim();
    if (val && !/^\d+(\.\d{1,2})?$/.test(val)) {
      isValid = false;
      errorMsgs.push('欄位 "' + (this.name || this.id) + '" 格式錯誤:最多兩位小數');
      $(this).addClass('is-invalid');
    } else {
      $(this).removeClass('is-invalid');
    }
  });
  
  $('.int-only').each(function() {
    var val = $(this).val().trim();
    if (val && !/^-?\d+$/.test(val)) {
      isValid = false;
      errorMsgs.push('欄位 "' + (this.name || this.id) + '" 必須為整數');
      $(this).addClass('is-invalid');
    }
  });
  
  if (!isValid) {
    alert(errorMsgs.join('\n'));
  }
  return isValid;
}

// 表單提交綁定
$('form').on('submit', function(e) {
  if (!validateNumericInputs()) {
    e.preventDefault();
  }
});

無 jQuery 輕量版 (現代瀏覽器)

// 原生 JS 版 (約 500 bytes gzipped)
document.querySelectorAll('.decimal-only').forEach(function(el) {
  ['input', 'paste'].forEach(function(evt) {
    el.addEventListener(evt, function() {
      var val = this.value.replace(/[^\d.]/g, '');
      var dot = val.indexOf('.');
      if (dot !== -1) {
        val = val.slice(0, dot + 1) + val.slice(dot + 1).replace(/\./g, '');
        if (val.length - dot > 3) val = val.slice(0, dot + 3);
      }
      this.value = val;
    });
  });
  el.style.imeMode = 'disabled';
});

這套方案已在多個電商、後台管理系統上線驗證,能有效應對各種邊界輸入情境,建議根據專案需求調整小數位數與負號支援策略。

copyright © 萬盛學電腦網 all rights reserved