如何使用正则表达式来限制数字?

时间:2018-01-17 05:28:42

标签: javascript html regex

以下代码仅接受keypress上的数字。如何按范围限制它。我想只接受12个字符。

const checkNumber = e => {
      const x = /[0-9]+/g;
       if (!x.test(e.key)) {
      e.preventDefault();
     }
    };

<input
   name="personnelID"
   type="text"
   className="form-control"
   required
   value={form.personnelID}
   onKeyPress={e => checkNumber(e)}
/>

更改为const x = /[0-9]{12,12}+/g;无效。请maxLength

提前致谢。

3 个答案:

答案 0 :(得分:0)

这仅限制数字:

^[0-9]{0,12}$

答案 1 :(得分:0)

你可以试试这个:

&#13;
&#13;
$('input').keypress(function( e ) {    
    var val=String.fromCharCode(e.which);
    if(e.keyCode != 8){  // releasing backspace you may add more here
    if(/[0-9]{12,}/.test(this.value) || !/[0-9]/.test(val))
        return false;
    }
    
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input  type="text" value=""   />
&#13;
&#13;
&#13;

答案 2 :(得分:0)

<label>Contact Number</label>
<input name="personnelID" id="subt"  required value="" placeholder="Enter Contact Number" onblur=checknumber(this) style="width: 235px;height: 40px;">
<label id="Invalidmessage" style="color:red;"></label>
<script>
function checknumber(e) {
//var IndNum = /^[0]?[789]\d{9}$/; //this will accept phone numbers of 10-digits starting with 789      
 var IndNum = /^[0-9]{10,12}$/;//this will accept numbers of 10,11,12-digits with in the range of 0-9
 var xx = e.value;
 if (IndNum.test(xx)) {      
        document.getElementById("Invalidmessage").innerHTML = "";           
        return true;
    }
    else {

        document.getElementById("Invalidmessage").innerHTML = "Invalid Mobile Number.";
        e.focus();

    }
}
</script>
  

希望这段代码有用。