1. 程式人生 > >html的input表單限制純數字及字元長度

html的input表單限制純數字及字元長度

1、限制字元長度用maxlength屬性

2、限制input輸入框為純數字:

a、onkeyup = "value=value.replace(/[^\d]/g,'')"

使用 onkeyup 事件,有 bug ,那就是在中文輸入法狀態下,輸入漢字之後直接回車,會直接輸入字母

b、onchange = "value=value.replace(/[^\d]/g,'')"

使用 onchange 事件,在輸入內容後,只有 input 喪失焦點時才會得到結果,並不能在輸入時就做出響應

c、oninput = "value=value.replace(/[^\d]/g,'')"

使用 oninput 事件,完美的解決了以上兩種問題,測試暫時還沒有出現其它問題。

程式碼示例:(11位手機號碼和4位驗證碼)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>input</title>
</head>
<body>
    <input type="text" placeholder="請輸入您的手機號" oninput = "value=value.replace(/[^\d]/g,'')" maxlength="11">
    <input type="text" placeholder="請輸入您的驗證碼" oninput = "value=value.replace(/[^\d]/g,'')" maxlength="4">
</body>
</html>

正則驗證11位手機號

function isPoneAvailable($poneInput) {  
      var myreg=/^[1][3,4,5,7,8][0-9]{9}$/;  
      if (!myreg.test($poneInput.val())) {  
         return false;  
      } else {  
         return true;  
      }  
} 

正則表示式:var myreg=/^[1][3,4,5,6,7,8,9][0-9]{9}$/;

1--以1為開頭;

2--第二位可為3,4,5,6,7,8,9中的任意一位;

3--最後以0-9的9個整數結尾。