在行動裝置表單中,針對電話、身分證、信用卡、數量等純數字欄位,使用 <input type="number"> 可自動喚起數字鍵盤(含 0-9、刪除、換行),大幅提升輸入效率。但需注意:type="number" 帶有微調箭頭、步進驗證、科學記號輸入等行為,不一定符合所有「純數字」場景。本文提供完整決策樹與替代方案。
需要輸入純數字
│
├─ 需要數值運算/比較/範圍限制(價格、數量、年齡、評分)
│ → ✅ 使用 type="number" + min/max/step
│
├─ 只是識別碼/代碼(身分證、信用卡、驗證碼、門牌號)
│ → ❌ 避免 type="number"(會出現微調箭頭、可能以科學記號顯示、去除前導零)
│ → ✅ 使用 type="text" + inputmode="numeric" + pattern="[0-9]*"
│
└─ 電話號碼
→ ✅ 使用 type="tel"(喚起電話鍵盤,含 * # +,無驗證邏輯)
| 屬性 | 說明 | 範例 |
|---|---|---|
min | 最小值 | min="0" |
max | 最大值 | max="100" |
step | 步進/驗證間距,any 允許任意小數 | step="0.01" (價格)、step="1" (整數) |
value | 初始值 | value="50" |
inputmode | 覆蓋鍵盤類型(獨立於 type) | inputmode="decimal" 強制顯示小數點 |
/* Chrome/Edge/Safari */
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
-webkit-appearance: none; margin: 0;
}
/* Firefox */
input[type="number"] { -moz-appearance: textfield; }
<!-- 身分證/信用卡/驗證碼:無微調箭頭、保留前導零、喚起數字鍵盤 -->
<input type="text"
inputmode="numeric"
pattern="[0-9]*"
placeholder="請輸入純數字"
autocomplete="off"
maxlength="16"
title="僅限數字">
<style>
/* 可選:視覺上區分數字欄位 */
input[inputmode="numeric"] { font-family: 'SF Mono', 'Roboto Mono', monospace; letter-spacing: 0.5ch; }
</style>
關鍵屬性說明:
inputmode="numeric":HTML 標準屬性,指示瀏覽器顯示數字鍵盤(支援 iOS 12.2+、Android Chrome 66+)。pattern="[0-9]*":iOS 舊版依據 pattern 決定鍵盤,雙重保險。autocomplete="off":避免密碼管理器誤填。maxlength:限制長度(信用卡 16、身分證 10、驗證碼 4-6)。<input type="tel" name="phone" placeholder="0912-345-678" autocomplete="tel">
<form>
<label>年齡 <input type="number" name="age" min="0" max="120" step="1" required></label>
<label>價格 <input type="number" name="price" min="0" step="0.01" required></label>
<label>信用卡 <input type="text" name="card" inputmode="numeric" pattern="[0-9]{13,19}" required maxlength="19"></label>
<button type="submit">送出</button>
</form>
<script>
// 送出前統一格式化
document.querySelector('form').addEventListener('submit', e => {
const card = e.target.card;
card.value = card.value.replace(/\s/g, ''); // 移除使用者可能輸入的空格
});
</script>
<label>(或 aria-label)。type="number" 的 min/max/step 錯誤訊息需本地化(瀏覽器預設英文)。aria-describedby 指向錯誤說明元素。總結:數值型用 type="number"、識別碼用 type="text" + inputmode="numeric" + pattern、電話用 type="tel",三者分工明確,能在所有主流行動瀏覽器獲得最佳鍵盤體驗與資料品質。