手機號碼、郵遞區號這類欄位只該收數字。做法是在 keyup 時把非數字的字元剔掉,再把結果寫回欄位。
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://code.jquery.com/jquery-1.9.0.min.js"></script>
</head>
<body>
<input type="text" id="phone" value="0000">
<script type="text/javascript">
jQuery(document).ready(function ($) {
var phone = $('#phone');
// 點進去時先清空預設值
phone.on('click', function () {
phone.val('');
});
phone.on('keyup', function () {
var phoneVal = phone.val();
phoneVal = phoneVal.replace('/[^\\d]+/g', ''); // 移除非數字字元
phoneVal = parseInt(phoneVal, 10);
if (isNaN(phoneVal)) {
phoneVal = '';
}
this.value = phoneVal;
});
});
</script>
</body>
</html>
一、正則寫錯了。 phoneVal.replace('/[^\\d]+/g', '') 的第一個參數是字串,不是正則物件,因此它會去找「字面上一長串 /[^\d]+/g」的文字,永遠找不到,過濾等於沒作用。正確寫法有兩種:
phoneVal.replace(/[^\d]/g, ''); // 正則物件,去掉斜線與引號
phoneVal.replace(new RegExp('[^0-9]', 'g'), '');
二、parseInt 會吃掉前導零。 parseInt("0912", 10) 得到 912,手機號碼開頭的 0 就這樣消失了。號碼是識別碼而不是數量,不該做數值轉換:
var phoneVal = phone.val().replace(/\D/g, ''); this.value = phoneVal; // 保留 "0912345678"
<label for="phone">手機號碼</label>
<input type="tel" id="phone" name="phone"
inputmode="numeric" pattern="[0-9]{9,10}"
maxlength="10" autocomplete="tel" placeholder="0912345678">
<script>
const phone = document.getElementById('phone');
phone.addEventListener('input', function () {
const cleaned = this.value.replace(/\D/g, ''); // \D = 非數字
if (cleaned !== this.value) {
this.value = cleaned;
}
});
phone.addEventListener('blur', function () {
if (!/^\d{9,10}$/.test(this.value)) {
showToast('請輸入 9 至 10 位數的號碼');
}
});
</script>
input 事件而非 keyup:keyup 抓不到以滑鼠右鍵貼上的內容,也處理不好中文輸入法與行動裝置的注音鍵盤。input 事件對所有輸入來源都會觸發。placeholder,它不會成為值的一部分。this.value 會讓游標移動,若使用者在中間插入文字就會錯亂。必要時要自行記錄並還原 selectionStart。- 或空白(0912-345-678),可依需求允許並在送出前統一移除;國際號碼還可能有 +。