数字和小数的输入掩码

21

我在测试我的程序后,意识到需要开发一个软件应用管理发票的功能。我发现以下错误: 我的SQL Server表包含:价格(numeric(6,2)) 当用户输入555.00时没有问题。 但是当他输入555555时就会出现错误,因此我需要指定掩码,其中尾数为可选的0到999,小数部分根据用户选择可编程为2或3。我正在使用jQuery Masked input插件,但是我没有找到好的正则表达式,请帮帮我。我正在使用JSP/servlet。


1
嗯...如果数据库字段是numeric(6,2),那么小数位数不能是“根据用户选择的2或3”。我错过了什么? - Mr Lister
是的,我在数据库中更改了它(6,3),小数点后面的两位或三位只是显示上的可选项。 - najeh22
但问题仍然存在。 - najeh22
我正在尝试使用正则表达式,但是我的正则表达式有误,导致出现错误。我的代码如下:var ex=/[0-9]{1-3}.[0-9]{2}。我想在输入小数时自动补全两个0,请帮忙解决。 - najeh22
我只需要强制小数点前的数字最多为14位数字,例如:用户可以输入从0.000到99999999999999.999的值。 - najeh22
显示剩余7条评论
8个回答

22
你可以使用jQuery numeric处理数字。
当前版本可以实现你需要的功能,但是有人稍微修改了一下代码,它也能正常工作:

HTML

<input class="numeric" type="text" />

JQuery

$(".numeric").numeric({ decimal : ".",  negative : false, scale: 3 });

这是整个源代码
我还准备了这个演示示例,让你可以看到它是如何工作的。


我尝试了这个http://jsfiddle.net/lun471k/4CHfC/,但是这里的正则表达式:/(\d{1,14})(\.\d{1,3}){0,1}$/(regex)是错误的。我需要你的帮助。 - najeh22
我只需要强制小数点前的数字最多为14位数字,例如:0.000到99999999999999.999。 - najeh22
当我使用精度为4时,我可以输入到9999,但我希望在精度为4的情况下得到的数值是99.99。 - najeh22
@najeh22:自定义插件。 - LeftyX
1
很遗憾,jquery.numeric不适用。在最近的浏览器中会产生大量错误。 - czjvic
显示剩余2条评论

12

使用 jQuery 输入掩码插件(6位整数和2位小数):

HTML:

使用jQuery输入掩码插件(6位整数和2位小数):

HTML:

<input class="mask" type="text" />

jQuery:

$(".mask").inputmask('Regex', {regex: "^[0-9]{1,6}(\\.\\d{1,2})?$"});

我希望这能帮助到某人。


1
我已经在桌面和移动设备上尝试了这个掩码。对我来说它不起作用。 - Michel Fernandes
让我更新一下:这是最好和最简单的掩码。它之前对我不起作用,因为在巴西葡萄牙语中我们使用“,”而不是“。”。 所以我们写1.000.000,00而不是像英语中的1,000,000.00。 因此,如果您的系统是葡萄牙语,请使用以下内容:$(".mask").inputmask('Regex', {regex: "^[0-9]{1,6}(\,\d{1,2})?$"});并不要忘记添加导入。 - Michel Fernandes
这个救了我的命。 - Dilip Hirapara

10

它也不能工作。输入显示为“1.5”,但应用程序却得到了“15”。 - Michel Fernandes
它对我有效。如果你想禁用rightAlign,你可以这样做:'rightAlign': false。这是我寻找已久的答案!非常感谢! - Gloria Chen

4
使用两个函数来解决它,非常简单有效:
HTML:
<input class="int-number" type="text" />
<input class="decimal-number" type="text" />

JQuery:

//Integer Number
$(document).on("input", ".int-number", function (e) {
  this.value = this.value.replace(/[^0-9]/g, '');
});

//Decimal Number
$(document).on("input", ".decimal-number", function (e) {
    this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');
});

它也不能正常工作。输入显示为“1.5”,但应用程序收到的是“15”。 - Michel Fernandes

2
或者也可以。
<input type="text" onkeypress="handleNumber(event, '€ {-10,3} $')" placeholder="€  $" size=25>

使用

function handleNumber(event, mask) {
    /* numeric mask with pre, post, minus sign, dots and comma as decimal separator
        {}: positive integer
        {10}: positive integer max 10 digit
        {,3}: positive float max 3 decimal
        {10,3}: positive float max 7 digit and 3 decimal
        {null,null}: positive integer
        {10,null}: positive integer max 10 digit
        {null,3}: positive float max 3 decimal
        {-}: positive or negative integer
        {-10}: positive or negative integer max 10 digit
        {-,3}: positive or negative float max 3 decimal
        {-10,3}: positive or negative float max 7 digit and 3 decimal
    */
    with (event) {
        stopPropagation()
        preventDefault()
        if (!charCode) return
        var c = String.fromCharCode(charCode)
        if (c.match(/[^-\d,]/)) return
        with (target) {
            var txt = value.substring(0, selectionStart) + c + value.substr(selectionEnd)
            var pos = selectionStart + 1
        }
    }
    var dot = count(txt, /\./, pos)
    txt = txt.replace(/[^-\d,]/g,'')

    var mask = mask.match(/^(\D*)\{(-)?(\d*|null)?(?:,(\d+|null))?\}(\D*)$/); if (!mask) return // meglio exception?
    var sign = !!mask[2], decimals = +mask[4], integers = Math.max(0, +mask[3] - (decimals || 0))
    if (!txt.match('^' + (!sign?'':'-?') + '\\d*' + (!decimals?'':'(,\\d*)?') + '$')) return

    txt = txt.split(',')
    if (integers && txt[0] && count(txt[0],/\d/) > integers) return
    if (decimals && txt[1] && txt[1].length > decimals) return
    txt[0] = txt[0].replace(/\B(?=(\d{3})+(?!\d))/g, '.')

    with (event.target) {
        value = mask[1] + txt.join(',') + mask[5]
        selectionStart = selectionEnd = pos + (pos==1 ? mask[1].length : count(value, /\./, pos) - dot) 
    }

    function count(str, c, e) {
        e = e || str.length
        for (var n=0, i=0; i<e; i+=1) if (str.charAt(i).match(c)) n+=1
        return n
    }
}

0
如果您的系统是英文的,请使用@Rick的答案:
如果您的系统是巴西葡萄牙语,请使用以下内容:
导入:
<script
        src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

    <script     src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.2.6/jquery.inputmask.bundle.min.js"></script>

HTML:

<input class="mask" type="text" />

JS:

$(".mask").inputmask('Regex', {regex: "^[0-9]{1,6}(\\,\\d{1,2})?$"});

这是因为在巴西葡萄牙语中,我们写作“1.000.000,00”,而不像英语中的“1,000,000.00”,因此如果使用“.”,系统将无法理解小数点。

就是这样,我希望它能帮助到某些人。我花了很多时间才明白这个问题。


0

现在我更好地理解了您的需求,这是我的建议。为您的文本框添加一个keyup处理程序,检查文本框内容是否与此正则表达式匹配:^[0-9]{1,14}\.[0-9]{2}$,如果不匹配,则将背景设置为红色或显示文本或其他您喜欢的方式。以下是要放在document.ready中的代码:

$(document).ready(function() {
    $('selectorForTextbox').bind('keyup', function(e) {
        if (e.srcElement.value.match(/^[0-9]{1,14}\.[0-9]{2}$/) === null) {
            $(this).addClass('invalid');
        } else {
            $(this).removeClass('invalid');
        }
    });
});

这里是一个 JSFiddle 的演示。同时,也要在服务器端执行相同的正则表达式,如果没有匹配,说明要求未满足。您还可以在 onsubmit 事件中进行检查,如果正则表达式不匹配,则不让用户提交页面。

不强制插入文本时使用掩码的原因是它会使事情变得非常复杂,例如我在评论中提到的那样,用户无法开始输入有效的输入,因为它的开头不是有效的。虽然这是可能的,但我建议使用这种方法代替。


“/^[0-9]{1,14}.[0-9]{2}$/” 不正确,有些问题,因为我可以输入任意数量的数字和字母。 - najeh22
我使用这个函数checkDec(el),但是正则表达式ex不正确: var ex=/^[0-9]{1,3}.[0-9]{2}$/; 如果(ex.test(el.value)==false),则执行以下操作: el.value = el.value.substring(0,el.value.length - 1); - najeh22
@najeh22 你可以输入任何你想要的内容,但是如果输入的文本无效,背景颜色会变成红色,这就是我所说的不强制使用掩码。无论如何,你都必须在服务器端进行验证,因此正则表达式应该用于服务器端验证和预提交。但是,如果你想要实时掩码,不允许您输入无效值,我建议您采用LeftyX的解决方案,因为这更加复杂(例如,您必须允许用户输入'2.',但那不是一个有效的值,因此会出现问题)。 - Bikonja
是的,你说得对,这就是我所说的。使用checkDec(el)函数时,正则表达式似乎有问题。 - najeh22
我有点难以理解你的意思。你能否创建一个 JSFiddle 并解释如何在其中查看问题?我希望这样可以消除困惑,然后我(或其他人)就能够理解到底是什么问题困扰着你。 - Bikonja

0
尝试使用imaskjs。它具有数字、正则表达式和其他掩码。非常简单易扩展。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接