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

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

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

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

当前回答

如果有人正在寻找一个正则表达式,只允许数字与可选的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);
});

其他回答

输入:

step="any"
class="two-decimals"

脚本:

$(".two-decimals").change(function(){
  this.value = parseFloat(this.value).toFixed(2);
});

关于货币,我建议:

<div><label>Amount $
    <input type="number" placeholder="0.00" required name="price" min="0" value="0" step="0.01" title="Currency" pattern="^\d+(?:\.\d{1,2})?$" onblur="
this.parentNode.parentNode.style.backgroundColor=/^\d+(?:\.\d{1,2})?$/.test(this.value)?'inherit':'red'
"></label></div>

参见http://jsfiddle.net/vx3axsk5/1/

HTML5属性“step”,“min”和“pattern”将在表单提交时验证,而不是onblur。如果你有一个模式,你就不需要步骤,如果你有一个步骤,你就不需要模式。因此,您可以使用我的代码返回到step="any",因为模式无论如何都会验证它。

If you'd like to validate onblur, I believe giving the user a visual cue is also helpful like coloring the background red. If the user's browser doesn't support type="number" it will fallback to type="text". If the user's browser doesn't support the HTML5 pattern validation, my JavaScript snippet doesn't prevent the form from submitting, but it gives a visual cue. So for people with poor HTML5 support, and people trying to hack into the database with JavaScript disabled or forging HTTP Requests, you need to validate on the server again anyways. The point with validation on the front-end is for a better user experience. So as long as most of your users have a good experience, it's fine to rely on HTML5 features provided the code will still works and you can validate on the back-end.

使用Javascript在文本框中只输入3个小数点。

<input type="text" class="form-control" onkeypress='return AllowOnlyAmountAndDot(this,event,true);/>

function AllowOnlyAmountAndDot(id, e, decimalbool) {    
    if(decimalbool == true) {   
        var t = id.value;
        var arr = t.split(".");
        var lastVal = arr.pop();
        var arr2 = lastVal.split('');
        if (arr2.length > '2') {
            e.preventDefault();
        } 
    }
}

你可以用这个。反应钩子

输入< 类型=“当家” name = "价格" 普莱斯placeholder =“回车” 一步=“任何” 所需 />

如果有人正在寻找一个正则表达式,只允许数字与可选的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);
});