javascript 将输入字段限制为一位小数点和两位小数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15252628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:03:31  来源:igfitidea点击:

Limiting input field to one decimal point and two decimal places

javascript

提问by Jonah

I have an input field which is limited to 6 characters. How can I validate my input field so that a user can't put more than one decimal point (i.e. 19..12), plus it can only be to two decimal places as well (i.e. 19.123)?

我有一个限制为 6 个字符的输入字段。如何验证我的输入字段,以便用户不能输入超过一个小数点(即 19..12),而且它也只能保留两位小数(即 19.123)?

This is my input field

这是我的输入字段

<input type="text" name="amount" id="amount" maxlength="6" autocomplete="off"/><span class="paymentalert" style="color:red;"></span>

Here is my validation script.

这是我的验证脚本。

$(function(){
$("#amount").keypress( function(e) {
    var chr = String.fromCharCode(e.which);
    if (".1234567890NOABC".indexOf(chr) < 0)
        return false;
});
});

$("#amount").blur(function() {
    var amount = parseFloat($(this).val());
    if (amount) {
        if (amount < 40 || amount > 200) {
            $("span.paymentalert").html("Your payment must be between £40 and £200");
        } else {
            $("span.paymentalert").html("");
        }
    } else {
        $("span.paymentalert").html("Your payment must be a number");
    }
});

Jonah

约拿

回答by Denys Séguret

This should do :

这应该做:

var ok = /^\d*\.?\d{0,2}$/.test(input);

(if I correctly understood that you don't want more than 2 digits after the dot)

(如果我正确理解您不希望点后超过 2 位数字)

The code thus would be :

因此,代码将是:

$("#amount").blur(function() {
    var input = $(this).val();
    if (/^\d*\.?\d{0,2}$/.test(input)) {
        var amount = parseFloat(input);
        if (amount < 40 || amount > 200) {
            $("span.paymentalert").html("Your payment must be between £40 and £200");
        } else {
            $("span.paymentalert").html("");
        }
    } else {
        $("span.paymentalert").html("Your payment must be a number");
    }
});

回答by talemyn

Assuming that:

假如说:

  1. There MUST have 2 digits after a decimal point, and
  2. There must be at least 2 digits before the decimal point, but no more than 3 digits
  1. 小数点后必须有 2 位数字,并且
  2. 小数点前必须至少有2位数字,但不能超过3位数字

The code you would use to match it would be:

你用来匹配它的代码是:

var value = $(this).val;
value.match(/^\d{2,3}(\.\d{2})?$/i);

回答by Michael H?rtl

It would be much easier if you used the Masked Input Pluginfor jQuery.

如果您使用jQuery的Masked Input Plugin会容易得多。