輸入框僅允許輸入數字,長度固定 11 位,失焦時校驗格式。
<script>
// 正則:開頭到結尾均為數字,恰好 11 位
var phoneReg = /^[\d]{11}$/;
function checkPhone(input) {
if (!phoneReg.test(input.value)) {
alert('只允許輸入 11 位數字');
input.select(); // 選中文本便於重新輸入
}
}
</script>
<input id="phoneNum" name="phoneNum" type="text"
value="${phoneNum}" maxlength="11"
onkeyup="this.value=this.value.replace(/\D/g,'')"
onafterpaste="this.value=this.value.replace(/\D/g,'')"
onblur="checkPhone(this)" />
replace(/\D/g,'') 實時剔除非數字字符,保證輸入框始終純數字。^1[3-9]\d{9}$)。input[type="tel"] 觸發移動端數字鍵盤。pattern 屬性實現原生表單驗證,減少 JS 代碼。