2010-05-11 96 views
85

如何限制輸入到文本框,以便它只接受數字和小數點?限制對文本框的輸入:僅允許數字和小數點

+9

他原來的問題是偉大的,阿馬爾... !!!爲什麼要改變它..? ;) – SpikETidE 2010-05-11 05:11:50

+11

爲什麼反對票?這個人在這裏是新的,幫助他改善他的追求,plz。 – lexu 2010-05-11 05:13:42

+0

Ayyappan.Anbalagan,在帖子中添加一些示例:) 所有這些字符串都適合您嗎? 192.168 192.168.0.1 – 2010-05-11 05:47:00

回答

132

<HTML> 
 
    <HEAD> 
 
    <SCRIPT language=Javascript> 
 
     <!-- 
 
     function isNumberKey(evt) 
 
     { 
 
      var charCode = (evt.which) ? evt.which : evt.keyCode; 
 
      if (charCode != 46 && charCode > 31 
 
      && (charCode < 48 || charCode > 57)) 
 
      return false; 
 

 
      return true; 
 
     } 
 
     //--> 
 
    </SCRIPT> 
 
    </HEAD> 
 
    <BODY> 
 
    <INPUT id="txtChar" onkeypress="return isNumberKey(event)" 
 
      type="text" name="txtChar"> 
 
    </BODY> 
 
</HTML>

這真的有效!

+1

爲什麼&& charCode> 31需要? – contactmatt 2012-08-29 21:01:24

+2

字符31是單元分隔符代碼。相當多的數字和文字在32和更高之間。代碼顯示,如果輸入的字符代碼不是十進制數AND高於31(單位分隔符)但低於48(數字0)或高於57(數字9),請不要接受它。 – 2012-11-02 00:24:36

+0

請添加參考來源:http://www.cambiaresearch.com/articles/39/how-can-i-use-javascript-to-allow-only-numbers-to-be-entered-in-a-文本框 – Bart 2012-11-05 05:18:21

23
form.onsubmit = function(){ 
    return textarea.value.match(/^\d+(\.\d+)?$/); 
} 

這是你要找的嗎?

我希望它有幫助。

編輯:我編輯我的例子上面,以便只能有一個時期,前面至少有一個數字,其次是至少一個數字。

+0

認爲這也將驗證'99 .23.65.86'.... 但我想這個問題是關於驗證'56987.32'單點......... – SpikETidE 2010-05-11 05:23:44

+0

我看到海報已編輯他/她原來的問題。感謝更新! – tau 2010-05-11 05:25:56

+2

嘗試使用^ \ d +(\。\ d +)?$ – Ben 2010-05-11 05:35:21

4

你在找這樣的事嗎?

<HTML> 
    <HEAD> 
    <SCRIPT language=Javascript> 
     <!-- 
     function isNumberKey(evt) 
     { 
     var charCode = (evt.which) ? evt.which : event.keyCode 
     if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) 
      return false; 

     return true; 
     } 
     //--> 
    </SCRIPT> 
    </HEAD> 
    <BODY> 
     <INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar"> 
    </BODY> 
    </HTML> 
+2

你錯過了點(小數點) – Ben 2010-05-11 05:31:54

+0

本,現在修好;) – 2010-05-11 05:43:55

1
inputelement.onchange= inputelement.onkeyup= function isnumber(e){ 
    e= window.event? e.srcElement: e.target; 
    while(e.value && parseFloat(e.value)+''!= e.value){ 
      e.value= e.value.slice(0, -1); 
    } 
} 
1
function integerwithdot(s, iid){ 
     var i; 
     s = s.toString(); 
     for (i = 0; i < s.length; i++){ 
      var c; 
      if (s.charAt(i) == ".") { 
      } else { 
       c = s.charAt(i); 
      } 
      if (isNaN(c)) { 
       c = ""; 
       for(i=0;i<s.length-1;i++){ 
        c += s.charAt(i); 
       } 
       document.getElementById(iid).value = c; 
       return false; 
      } 
     } 
     return true; 
    } 
1

這裏是腳本,CAS幫助您:

<script type="text/javascript"> 
// price text-box allow numeric and allow 2 decimal points only 
function extractNumber(obj, decimalPlaces, allowNegative) 
{ 
    var temp = obj.value; 

    // avoid changing things if already formatted correctly 
    var reg0Str = '[0-9]*'; 
    if (decimalPlaces > 0) { 
     reg0Str += '\[\,\.]?[0-9]{0,' + decimalPlaces + '}'; 
    } else if (decimalPlaces < 0) { 
     reg0Str += '\[\,\.]?[0-9]*'; 
    } 
    reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str; 
    reg0Str = reg0Str + '$'; 
    var reg0 = new RegExp(reg0Str); 
    if (reg0.test(temp)) return true; 

    // first replace all non numbers 
    var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (decimalPlaces != 0 ? ',' : '') + (allowNegative ? '-' : '') + ']'; 
    var reg1 = new RegExp(reg1Str, 'g'); 
    temp = temp.replace(reg1, ''); 

    if (allowNegative) { 
     // replace extra negative 
     var hasNegative = temp.length > 0 && temp.charAt(0) == '-'; 
     var reg2 = /-/g; 
     temp = temp.replace(reg2, ''); 
     if (hasNegative) temp = '-' + temp; 
    } 

    if (decimalPlaces != 0) { 
     var reg3 = /[\,\.]/g; 
     var reg3Array = reg3.exec(temp); 
     if (reg3Array != null) { 
      // keep only first occurrence of . 
      // and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0 
      var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length); 
      reg3Right = reg3Right.replace(reg3, ''); 
      reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right; 
      temp = temp.substring(0,reg3Array.index) + '.' + reg3Right; 
     } 
    } 

    obj.value = temp; 
} 
function blockNonNumbers(obj, e, allowDecimal, allowNegative) 
{ 
    var key; 
    var isCtrl = false; 
    var keychar; 
    var reg; 
    if(window.event) { 
     key = e.keyCode; 
     isCtrl = window.event.ctrlKey 
    } 
    else if(e.which) { 
     key = e.which; 
     isCtrl = e.ctrlKey; 
    } 

    if (isNaN(key)) return true; 

    keychar = String.fromCharCode(key); 

    // check for backspace or delete, or if Ctrl was pressed 
    if (key == 8 || isCtrl) 
    { 
     return true; 
    } 

    reg = /\d/; 
    var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false; 
    var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false; 
    var isFirstC = allowDecimal ? keychar == ',' && obj.value.indexOf(',') == -1 : false; 
    return isFirstN || isFirstD || isFirstC || reg.test(keychar); 
} 
function blockInvalid(obj) 
{ 
    var temp=obj.value; 
    if(temp=="-") 
    { 
     temp=""; 
    } 

    if (temp.indexOf(".")==temp.length-1 && temp.indexOf(".")!=-1) 
    { 
     temp=temp+"00"; 
    } 
    if (temp.indexOf(".")==0) 
    { 
     temp="0"+temp; 
    } 
    if (temp.indexOf(".")==1 && temp.indexOf("-")==0) 
    { 
     temp=temp.replace("-","-0") ; 
    } 
    if (temp.indexOf(",")==temp.length-1 && temp.indexOf(",")!=-1) 
    { 
     temp=temp+"00"; 
    } 
    if (temp.indexOf(",")==0) 
    { 
     temp="0"+temp; 
    } 
    if (temp.indexOf(",")==1 && temp.indexOf("-")==0) 
    { 
     temp=temp.replace("-","-0") ; 
    } 
    temp=temp.replace(",",".") ; 
    obj.value=temp; 
} 
// end of price text-box allow numeric and allow 2 decimal points only 
</script> 

<input type="Text" id="id" value="" onblur="extractNumber(this,2,true);blockInvalid(this);" onkeyup="extractNumber(this,2,true);" onkeypress="return blockNonNumbers(this, event, true, true);"> 
1

假設你的文本字段名爲Income
電話時,需要驗證你的領域這個validate方法:

function validate() { 
    var currency = document.getElementById("Income").value; 
     var pattern = /^[1-9]\d*(?:\.\d{0,2})?$/ ; 
    if (pattern.test(currency)) { 
     alert("Currency is in valid format"); 
     return true; 
    } 
     alert("Currency is not in valid format!Enter in 00.00 format"); 
     return false; 
} 
0
function isNumberKey(evt) 
{ 
    var charCode = (evt.which) ? evt.which : evt.keyCode; 

    if(charCode==8 || charCode==13|| charCode==99|| charCode==118 || charCode==46) 
    {  
     return true; 
    } 

    if (charCode > 31 && (charCode < 48 || charCode > 57)) 
    { 
     return false; 
    } 
    return true; 
} 

它將只允許數字,並會讓你把「」爲十進制。

2

對於任何磕磕絆絆這裏像我一樣,這裏是一個jQuery 1.10.2版本,我寫了這是爲我工作得很好儘管資源密集型:

/*************************************************** 
* Only allow numbers and one decimal in text boxes 
***************************************************/ 
$('body').on('keydown keyup keypress change blur focus paste', 'input[type="text"]', function(){ 
    var target = $(this); 

    var prev_val = target.val(); 

    setTimeout(function(){ 
     var chars = target.val().split(""); 

     var decimal_exist = false; 
     var remove_char = false; 

     $.each(chars, function(key, value){ 
      switch(value){ 
       case '0': 
       case '1': 
       case '2': 
       case '3': 
       case '4': 
       case '5': 
       case '6': 
       case '7': 
       case '8': 
       case '9': 
       case '.': 
        if(value === '.'){ 
         if(decimal_exist === false){ 
          decimal_exist = true; 
         } 
         else{ 
          remove_char = true; 
          chars[''+key+''] = ''; 
         } 
        } 
        break; 
       default: 
        remove_char = true; 
        chars[''+key+''] = ''; 
        break; 
      } 
     }); 

     if(prev_val != target.val() && remove_char === true){ 
      target.val(chars.join('')) 
     } 
    }, 0); 
}); 
2

小幅回調至@ rebisco的輝煌答案來驗證十進制完美。

function isNumberKey(evt) { 
    debugger; 
    var charCode = (evt.which) ? evt.which : event.keyCode; 
    if (charCode == 46 && evt.srcElement.value.split('.').length>1) { 
     return false; 
    } 
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) 
     return false; 
    return true; 
} 
+0

這是非常好的。但是,我想將它限制在2個小數點,無論如何要做到這一點? – nodeffect 2015-06-09 07:02:04

0
<script type="text/javascript"> 

    function isNumberKey(evt) { 
     var charCode = (evt.which) ? evt.which : event.keyCode; 
     if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) 
      return false; 

     return true; 
    } 

</script> 

@Html.EditorFor(model => model.Orderids, new { id = "Orderids", Onkeypress=isNumberKey(event)}) 

這工作得很好。

3

只需要在Jquery中應用此方法,您可以驗證您的文本框只接受只有小數的數字。

function IsFloatOnly(element) {  
var value = $(element).val(); 
var regExp ="^\\d+(\\.\\d+)?$"; 
return value.match(regExp); 
} 

請參閱工作演示here

+0

一個演示的唯一反應,效果很好.. :) – Rohit416 2014-02-18 09:41:47

0

從@rebisco答案開始:

function count_appearance(mainStr, searchFor) { 
    return (mainStr.split(searchFor).length - 1); 
} 
function isNumberKey(evt) 
{ 
    $return = true; 
    var charCode = (evt.which) ? evt.which : event.keyCode; 
    if (charCode != 46 && charCode > 31 
      && (charCode < 48 || charCode > 57)) 
     $return = false; 
    $val = $(evt.originalTarget).val(); 
    if (charCode == 46) { 
     if (count_appearance($val, '.') > 0) { 
      $return = false; 
     } 
     if ($val.length == 0) { 
      $return = false; 
     } 
    } 
    return $return; 
} 

只允許以下格式:123123123 [0.121213]

演示這裏demo

1

擴展@ rebisco的答案。下面的代碼將只允許在文本框中輸入數字和單個'。'(句號)。

function isNumberKey(evt) { 
     var charCode = (evt.which) ? evt.which : event.keyCode; 
     if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) { 
      return false; 
     } else { 
      // If the number field already has . then don't allow to enter . again. 
      if (evt.target.value.search(/\./) > -1 && charCode == 46) { 
       return false; 
      } 
      return true; 
     } 
    } 
1

希望它能爲你工作。

<input type="text" onkeypress="return chkNumeric(event)" /> 

<script> 
    function chkNumeric(evt) { 
     evt = (evt) ? evt : window.event; 
     var charCode = (evt.which) ? evt.which : evt.keyCode; 
     if (charCode > 31 && (charCode < 48 || charCode > 57)) { 
      if (charCode == 46) { return true; } 
      else { return false; } 
     } 
     return true; 
    } 
</script> 
15

由於您可以輸入多個'。',例如24 .... 22..22,因此接受的解決方案並不完整。與一些小的修改,將工作打算:

<HTML><HEAD> 
<script type="text/javascript"> 

function isNumberKey(txt, evt) { 

    var charCode = (evt.which) ? evt.which : evt.keyCode; 
    if (charCode == 46) { 
     //Check if the text already contains the . character 
     if (txt.value.indexOf('.') === -1) { 
      return true; 
     } else { 
      return false; 
     } 
    } else { 
     if (charCode > 31 
      && (charCode < 48 || charCode > 57)) 
      return false; 
    } 
    return true; 
} 

</SCRIPT></HEAD><BODY> 
<input type="text" onkeypress="return isNumberKey(this, event);" /> </BODY></HTML> 
+0

我用你的答案,但我修改此onkeypress =「返回isNumberKey(this,事件);」 – 2015-05-28 12:12:13

+0

是的,我認爲這是可選的鍵入傳遞事件,因爲它適用於這兩種情況,謝謝 – 2015-05-30 05:14:34

1

更好的解決方案

var checkfloats = function(event){ 
    var charCode = (event.which) ? event.which : event.keyCode; 
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) 
     return false; 

    if(event.target.value.indexOf('.') >=0 && charCode == 46) 
     return false; 

    return true; 
} 
8

這裏是一個多解決方案,它允許十進制數,也限制了小數點後位數爲2位小數。

function isNumberKey(evt, element) { 
 
    var charCode = (evt.which) ? evt.which : event.keyCode 
 
    if (charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode == 46 || charcode == 8)) 
 
    return false; 
 
    else { 
 
    var len = $(element).val().length; 
 
    var index = $(element).val().indexOf('.'); 
 
    if (index > 0 && charCode == 46) { 
 
     return false; 
 
    } 
 
    if (index > 0) { 
 
     var CharAfterdot = (len + 1) - index; 
 
     if (CharAfterdot > 3) { 
 
     return false; 
 
     } 
 
    } 
 

 
    } 
 
    return true; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="number" id="rate" placeholder="Billing Rate" required onkeypress="return isNumberKey(event,this)">

+0

完美的答案... – 2015-11-13 10:53:31

+0

幾乎完美..你的'if'的最後一個條件是缺少大寫的「C」。 – DNKROZ 2017-08-03 12:13:23

0

下面的代碼爲我工作

與 「onkeypress事件」 事件作爲輸入框如下

<input type="text" onkeypress="return isNumberKey(this,event);" /> 

功能 「isNumberKey」 如下

function isNumberKey(txt, evt) { 
 
    var charCode = (evt.which) ? evt.which : evt.keyCode; 
 
    if (charCode == 46) { 
 
    //Check if the text already contains the . character 
 
    if (txt.value.indexOf('.') === -1) { 
 
     return true; 
 
    } else { 
 
     return false; 
 
    } 
 
    } else { 
 
    if (charCode > 31 && (charCode < 48 || charCode > 57)) 
 
     return false; 
 
    } 
 
    return true; 
 
}

0

我觀察到,所有的答案在這裏提供的東西都沒有,如果我們選擇在文本框中的文本的某些部分,並試圖覆蓋的那部分工作。 所以我修改的是如下的功能:

<HTML> 
    <HEAD> 
    <SCRIPT language=Javascript> 
     <!-- 
     function isNumberKey(evt) 
     { 
     var charCode = (evt.which) ? evt.which : event.keyCode; 

if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) 
{ 
     return false; 
} 
if (charCode == 46 && evt.srcElement.value.split('.').length>1) 
    { 

     return false; 

    } 

if(evt.srcElement.selectionStart<evt.srcElement.selectionEnd) 
    { 
      return true; 
    } 

    if(evt.srcElement.value.split('.').length>1 && evt.srcElement.value.split('.')[1].length==2) 
    { 

    return false; 
    } 


    return true; 
     } 


     //--> 
    </SCRIPT> 
    </HEAD> 
    <BODY> 
    <INPUT id="txtChar" onkeypress="return isNumberKey(event)" 
      type="text" name="txtChar"> 
    </BODY> 
</HTML> 
0

十進制數,也允許有2個地方否定號碼後點小數......我修改的功能:

<input type="text" id="txtSample" onkeypress="return isNumberKey(event,this)"/> 



function isNumberKey(evt, element){ 

     var charCode = (evt.which) ? evt.which : event.keyCode 
     if (charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode == 46 || charCode == 8 || charCode == 45)) 
      return false; 
     else { 
      var len = $(element).val().length; 

      // Validation Point 
      var index = $(element).val().indexOf('.'); 
      if ((index > 0 && charCode == 46) || len == 0 && charCode == 46) { 
       return false; 
      } 
      if (index > 0) { 
       var CharAfterdot = (len + 1) - index; 
       if (CharAfterdot > 3) { 
        return false; 
       } 
      } 

      // Validating Negative sign 
      index = $(element).val().indexOf('-'); 
      if ((index > 0 && charCode == 45) || (len > 0 && charCode == 45)) { 
       return false; 
      } 
     } 
     return true; 
    } 
-1
<input type="text" class="number_only" />  
<script> 
$(document).ready(function() { 
    $('.number_only').keypress(function (event) { 
     return isNumber(event, this) 
    });   
}); 

function isNumber(evt, element) { 
    var charCode = (evt.which) ? evt.which : event.keyCode 

    if ((charCode != 45 || $(element).val().indexOf('-') != -1) && (charCode != 46 || $(element).val().indexOf('.') != -1) && ((charCode < 48 && charCode != 8) || charCode > 57)){ 
     return false; 
    } 
    else { 
     return true; 
    } 
} 
</script> 

http://www.encodedna.com/2013/05/enter-only-numbers-using-jquery.htm

0

替代的方式來限制輸入到文本框,以便它僅接受數字和小數點是 在html輸入中使用javascript。這個工作對我來說:

<input type="text" class="form-control" id="price" name="price" placeholder="Price" 
vrequired onkeyup="this.value=this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1')"> 

--Accepts--

9.99

--Do不accept--

9.99。99

ABC

-1
document.getElementById('value').addEventListener('keydown', function(e) { 
    var key = e.keyCode ? e.keyCode : e.which; 

/*lenght of value to use with index to know how many numbers after.*/ 

    var len = $('#value').val().length; 
    var index = $('#value').val().indexOf('.'); 
    if (!([8, 9, 13, 27, 46, 110, 190].indexOf(key) !== -1 || 
        (key == 65 && (e.ctrlKey || e.metaKey )) || 
        (key >= 35 && key <= 40) || 
        (key >= 48 && key <= 57 && !(e.shiftKey || e.altKey)) || 
        (key >= 96 && key <= 105) 
      )){ 
     e.preventDefault(); 
    } 

/*if theres a . count how many and if reachs 2 digits after . it blocks*/ 

    if (index > 0) { 
     var CharAfterdot = (len + 1) - index; 
     if (CharAfterdot > 3) { 

/*permits the backsapce to remove :D could be improved*/ 

      if (!(key == 8)) 
      { 
       e.preventDefault(); 
      } 

/*blocks if you try to add a new . */ 

     }else if (key == 110) { 
      e.preventDefault(); 
     } 

/*if you try to add a . and theres no digit yet it adds a 0.*/ 

    } else if(key == 110&& len==0){ 
     e.preventDefault(); 
     $('#value').val('0.'); 
    } 
}); 
+0

允許2位小數,如果您添加一個。它增加了0.並且限制爲1。和2位十進制 – buga 2016-10-20 16:33:10

+0

代碼的一些解釋是有用的。此外,您的評論下的答案應該作爲答案的一部分,作爲補充說明。 – 2016-10-20 16:57:37

0

最佳,並與純JavaScript的樣本 現場演示工作液:https://jsfiddle.net/manoj2010/ygkpa89o/

<script> 
 
function removeCommas(nStr) { 
 
    if (nStr == null || nStr == "") 
 
     return ""; 
 
    return nStr.toString().replace(/,/g, ""); 
 
} 
 

 
function NumbersOnly(myfield, e, dec,neg) 
 
{   
 
    if (isNaN(removeCommas(myfield.value)) && myfield.value != "-") { 
 
     return false; 
 
    } 
 
    var allowNegativeNumber = neg || false; 
 
    var key; 
 
    var keychar; 
 

 
    if (window.event) 
 
     key = window.event.keyCode; 
 
    else if (e) 
 
     key = e.which; 
 
    else 
 
     return true; 
 
    keychar = String.fromCharCode(key); 
 
    var srcEl = e.srcElement ? e.srcElement : e.target;  
 
    // control keys 
 
    if ((key == null) || (key == 0) || (key == 8) || 
 
       (key == 9) || (key == 13) || (key == 27)) 
 
     return true; 
 

 
    // numbers 
 
    else if ((("").indexOf(keychar) > -1)) 
 
     return true; 
 

 
    // decimal point jump 
 
    else if (dec && (keychar == ".")) { 
 
     //myfield.form.elements[dec].focus(); 
 
     return srcEl.value.indexOf(".") == -1;   
 
    } 
 

 
    //allow negative numbers 
 
    else if (allowNegativeNumber && (keychar == "-")) {  
 
     return (srcEl.value.length == 0 || srcEl.value == "0.00") 
 
    } 
 
    else 
 
     return false; 
 
} 
 
</script> 
 
<input name="txtDiscountSum" type="text" onKeyPress="return NumbersOnly(this, event,true)" />

0

工作的問題我自己,這就是我的本錢至今。這或多或少的作用,但由於新的值檢查,不可能在之後添加減號。也不允許逗號作爲千位分隔符,只有小數。

這並不完美,但可能會提供一些想法。

app.directive('isNumber', function() { 
      return function (scope, elem, attrs) { 
       elem.bind('keypress', function (evt) { 
        var keyCode = (evt.which) ? evt.which : event.keyCode; 
        var testValue = (elem[0].value + String.fromCharCode(keyCode) + "0").replace(/ /g, ""); //check ignores spaces 
        var regex = /^\-?\d+((\.|\,)\d+)?$/;       
        var allowedChars = [8,9,13,27,32,37,39,44,45, 46] //control keys and separators    

        //allows numbers, separators and controll keys and rejects others 
        if ((keyCode > 47 && keyCode < 58) || allowedChars.indexOf(keyCode) >= 0) {    
         //test the string with regex, decline if doesn't fit 
         if (elem[0].value != "" && !regex.test(testValue)) { 
          event.preventDefault(); 
          return false; 
         } 
         return true; 
        } 
        event.preventDefault(); 
        return false; 
       }); 
      }; 
     }); 

允許:

11 11 0.245(在格式化上模糊到1111.245控制器)

11,44

-123.123

-1 014

0123(格式化爲123模糊)

不允許:

@#$/*

ABC

11.11.1

11,11.1

0.42

3

所有的解決方案呈現!這裏使用單個關鍵事件。這很容易出錯,因爲輸入也可以使用copy'n'paste或drag'n'drop。還有一些解決方案限制非字符鍵的使用,如ctrl+cPos1等。

我建議您不要檢查每個按鍵,而是檢查結果是否與您的期望相符。

var validNumber = new RegExp(/^\d*\.?\d*$/); 
 
var lastValid = document.getElementById("test1").value; 
 
function validateNumber(elem) { 
 
    if (validNumber.test(elem.value)) { 
 
    lastValid = elem.value; 
 
    } else { 
 
    elem.value = lastValid; 
 
    } 
 
}
<textarea id="test1" oninput="validateNumber(this);" ></textarea>

oninput事件被觸發後立即考研,在文本區和正在呈現之前改變。

您可以將RegEx擴展爲您想要接受的任何數字格式。這比檢查單個按鍵更具可維護性和可擴展性。

+0

它接受'.'作爲有效的輸入。 – Andrew 2017-05-10 02:21:50

+0

@Andrew所以做一些編程語言。評估 」。」浮動通常導致「0.0」。 – 2017-07-13 00:33:17

+0

這是最優雅的解決方案! – jkd 2017-10-24 08:27:04

0
<input type="text" onkeypress="return isNumberKey(event,this)"> 

<script> 
    function isNumberKey(evt, obj) { 

      var charCode = (evt.which) ? evt.which : event.keyCode 
      var value = obj.value; 
      var dotcontains = value.indexOf(".") != -1; 
      if (dotcontains) 
       if (charCode == 46) return false; 
      if (charCode == 46) return true; 
      if (charCode > 31 && (charCode < 48 || charCode > 57)) 
       return false; 
      return true; 
     } 


</script> 
0

如果你想爲浮點值,

這裏是我使用

<HTML> 
 

 
<HEAD> 
 
    <SCRIPT language=Javascript> 
 
    <!-- 
 
    function check(e, value) { 
 
     //Check Charater 
 
     var unicode = e.charCode ? e.charCode : e.keyCode; 
 
     if (value.indexOf(".") != -1) 
 
     if (unicode == 46) return false; 
 
     if (unicode != 8) 
 
     if ((unicode < 48 || unicode > 57) && unicode != 46) return false; 
 
    } 
 
    //--> 
 
    </SCRIPT> 
 
</HEAD> 
 

 
<BODY> 
 
    <INPUT id="txtChar" onkeypress="return check(event,value)" type="text" name="txtChar"> 
 
</BODY> 
 

 
</HTML>

0

我知道這個問題是很老的功能,但我們仍然往往得到這樣的要求。有很多例子,但很多似乎太詳細複雜一個簡單的implimentation。

看到這個https://jsfiddle.net/vibs2006/rn0fvxuk/並改進它(如果可以的話)。它適用於IE,Firefox,Chrome和Edge瀏覽器。

這裏是工作代碼。

  
 
     function IsNumeric(e) { 
 
     var IsValidationSuccessful = false; 
 
     console.log(e.target.value); 
 
     document.getElementById("info").innerHTML = "You just typed ''" + e.key + "''"; 
 
     //console.log("e.Key Value = "+e.key); 
 
     switch (e.key) 
 
     {   
 
      case "1": 
 
      case "2": 
 
      case "3": 
 
      case "4": 
 
      case "5": 
 
      case "6": 
 
      case "7": 
 
      case "8": 
 
      case "9": 
 
      case "0": 
 
      case "Backspace":    
 
       IsValidationSuccessful = true; 
 
       break; 
 
        
 
\t \t \t \t \t \t case "Decimal": //Numpad Decimal in Edge Browser 
 
      case ".":  //Numpad Decimal in Chrome and Firefox      
 
      case "Del": \t \t \t // Internet Explorer 11 and less Numpad Decimal 
 
       if (e.target.value.indexOf(".") >= 1) //Checking if already Decimal exists 
 
       { 
 
        IsValidationSuccessful = false; 
 
       } 
 
       else 
 
       { 
 
        IsValidationSuccessful = true; 
 
       } 
 
       break; 
 

 
      default: 
 
       IsValidationSuccessful = false; 
 
     } 
 
     //debugger; 
 
     if(IsValidationSuccessful == false){ 
 
      
 
     document.getElementById("error").style = "display:Block"; 
 
     }else{ 
 
     document.getElementById("error").style = "display:none"; 
 
     } 
 
      
 
     return IsValidationSuccessful; 
 
     }
Numeric Value: <input type="number" id="text1" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" /><br /> 
 
    <span id="error" style="color: Red; display: none">* Input digits (0 - 9) and Decimals Only</span><br /> 
 
    <div id="info"></div>

相關問題