var p = /^[\d]{11}$/; // 正則 表示 開頭為數字 要11位 結尾
function chk(n) { // 檢測函數
if(!p.test(n.value)) { // 檢測值input的值是否由數字組合並要11位 如果不是則提示
alert('只允許數字並要11位');
n.select(); // 選中輸入框內容
}
}
<input id="phoneNum" name="phoneNum" value="${phoneNum}" type="text" onkeyup="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')" onblur="chk(this)" maxlength="11"/>
以上代碼校驗輸入框是否是11位數字