我有一个<input type="number">,我想将用户的输入限制为纯数字或带有小数点后最多2位的数字。

基本上,我是在要求一个价格输入。

我想避免使用正则表达式。有办法吗?

<input type="number" required name="price" min="0" value="0" step="any">

当前回答

  <input type="number" class="form-control" id="price" oninput="validate(this)" placeholder="Enter price" name="price" style="width:50%;">

  var validate = function(e) {
      var t = e.value;
      e.value = (t.indexOf(".") >= 0) ? (t.substr(0, t.indexOf(".")) + t.substr(t.indexOf("."), 3)) : t;
  }

其他回答

试着在输入类型中只允许2个小数

<input type="number" step="0.01" class="form-control"  />

或者使用jQuery的建议@SamohtVII

$( "#ELEMENTID" ).blur(function() {
    this.value = parseFloat(this.value).toFixed(2);
});

使用step="而不是step="any",因为它允许小数位数任意。“01”,最多允许小数点后两位。

更多详细信息见规范:https://www.w3.org/TR/html/sec-forms.html#the-step-attribute

这是我想出的解决方案,它还可以阻止用户输入超过2个小数,上面提到的许多解决方案都不能防止这种情况

html:

<input autocomplete="off" type="number" id="priceField" step=".01" min="0" onkeypress="return priceCheck(this, event);"

Javascript:

function priceCheck(element, event) {
    result = (event.charCode >= 48 && event.charCode <= 57) || event.charCode === 46;
    if (result) {
        let t = element.value;
        if (t === '' && event.charCode === 46) {
            return false;
        }
        let dotIndex = t.indexOf(".");
        let valueLength = t.length;
        if (dotIndex > 0) {
            if (dotIndex + 2 < valueLength) {
                return false;
            } else {
                return true;
            }
        } else if (dotIndex === 0) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

I had the same requirement but after checking all these answers I realized there is no inbuilt support to block users from typing a particular number of decimal points. step="0.01" is useful when validating the input for a decimal number but still it will not block users from typing any decimal. In my case, I wanted a solution which will prevent user from entering invalid decimal. So I created my own custom JavaScript function which will enforce user any decimal rule. There is a slight performance issue but for my scenario it is okay to have a very small delay to make sure that user is not typing invalid decimal places. It might be useful for someone who wanted to prevent user from typing invalid decimal value on the input.

如果您愿意,可以使用step="0.01"来使用此解决方案。你可以在元素oninput事件上使用下面的函数。如果性能对你来说很重要,那么考虑使用onchange事件而不是oninput。请在data-decimal属性中指定允许输入的最大小数位数。它的值可以从0到任何数字。

function enforceNumberValidation(ele) { if ($(ele).data('decimal') != null) { // found valid rule for decimal var decimal = parseInt($(ele).data('decimal')) || 0; var val = $(ele).val(); if (decimal > 0) { var splitVal = val.split('.'); if (splitVal.length == 2 && splitVal[1].length > decimal) { // user entered invalid input $(ele).val(splitVal[0] + '.' + splitVal[1].substr(0, decimal)); } } else if (decimal == 0) { // do not allow decimal place var splitVal = val.split('.'); if (splitVal.length > 1) { // user entered invalid input $(ele).val(splitVal[0]); // always trim everything after '.' } } } } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="number" data-decimal="0" oninput="enforceNumberValidation(this)" placeholder="No decimal places" value="" /> <input type="number" data-decimal="2" oninput="enforceNumberValidation(this)" placeholder="2 decimal places" value="" /> <input type="number" data-decimal="5" oninput="enforceNumberValidation(this)" placeholder="5 decimal places" value="" />

我可以使用RegExp来识别无效值,但我还必须恢复输入中的更改。所以我决定不使用RegExp。

如果有人正在寻找一个正则表达式,只允许数字与可选的2小数点后

^\d*(\.\d{0,2})?$

例如,我发现下面的解决方案相当可靠

HTML:

<input name="my_field" pattern="^\d*(\.\d{0,2})?$" />

JS / JQuery:

$(document).on('keydown', 'input[pattern]', function(e){
  var input = $(this);
  var oldVal = input.val();
  var regex = new RegExp(input.attr('pattern'), 'g');

  setTimeout(function(){
    var newVal = input.val();
    if(!regex.test(newVal)){
      input.val(oldVal); 
    }
  }, 1);
});