如何通过从数字键盘输入来验证小数点后两位的输入值?

时间:2017-05-23 08:01:13

标签: javascript jquery html html5

我有一个JavaScript函数来仅验证十进制值。我使用JavaScript onkeyup事件。



function onlyNumeric(evt) {
  var theEvent = evt || window.event;
  var key = theEvent.keyCode || theEvent.which;
  var exclusions = [8, 46];

  if (exclusions.indexOf(key) > -1) {
    return;
  }

  key = String.fromCharCode(key);

  var regex = /[0-9]|\./;

  if (!regex.test(key)) {
    theEvent.returnValue = false;

    if (theEvent.preventDefault) {
      theEvent.preventDefault();
    }

    return false;
  }

  return true;
}

<input type="text" onkeyup="onlyNumeric(event)" class="form-control" id="ColumnName" name="ColumnName">
&#13;
&#13;
&#13;

当我把数值放在数字键盘上时,它工作正常。但是,当我用数字键盘放价值时,它不起作用。那么我该如何解决呢?

另外我需要在小数点后两位修复它。但是我怎么能这样做呢?

onkeyup事件是否可以用于此目的?

3 个答案:

答案 0 :(得分:2)

以下是帮助您解决问题的代码:

function onlyNumeric(evt) {
    var pattern = /^\d{0,4}(\.\d{0,2})?$/i;
    var element = document.getElementById("ColumnName");
    if(pattern.test(element.value)) {
      console.log("Vadid number:" + element.value);
    } else {
      console.log("Invadid number:" + element.value);
    }
}
<input type="text" onkeyup="onlyNumeric(event)" class="form-control" id="ColumnName" name="ColumnName">

答案 1 :(得分:2)

您可以使用此正则表达式模式:

/^\d+(?:\.\d{1,2})?$/ 

说明:

\d    match a digit...   
+     one or more times    
(     begin group...     
?:    but do not capture anything     
\.    match literal dot     
\d    match a digit...     
{1,2} one or two times    
)     end group   
?     make the entire group optional 

&#13;
&#13;
<input type="text" onkeyup="onlyNumeric(event)" class="form-control" id="ColumnName" name="ColumnName">

<script>
function onlyNumeric(evt) {
    var rx = /^\d+(?:\.\d{1,2})?$/;
    var ele = document.getElementById("ColumnName");
    if(rx.test(ele.value)) { 
       console.log("true");
    }else{ 
       console.log("false");
    }
}
</script>
&#13;
&#13;
&#13;

使用addEventListener()代替onkeyup的另一种解决方案:

&#13;
&#13;
<input type="text" class="form-control" id="ColumnName" name="ColumnName">

<script>
function onlyNumeric(evt) {
    var rx = /^\d+(?:\.\d{1,2})?$/;
    var ele = document.getElementById("ColumnName");
    if(rx.test(ele.value)) { 
       console.log("true");
    }else{ 
       console.log("false");
    }
}

var el = document.getElementById("ColumnName");
el.addEventListener("input", onlyNumeric, false);

</script>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

使用此jquery插件,它在键入和鼠标单击时验证十进制行为 https://github.com/sarkfoundation/Decimal-Behavior

   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type='text/javascript' src="https://rawgit.com/sarkfoundation/Decimal-Behavior/master/sark-decimal/sark-decimal.js"></script>
    <input type="text" data-behaviour="decimal">