jQuery 数字和十进制的输入掩码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18269742/
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-08-26 21:18:22  来源:igfitidea点击:

Input mask for numeric and decimal

javascriptjqueryhtmlregexinput-mask

提问by najeh22

I realized a software application management invoicing after having tested my program I noticed the following error: my table in sqlserver contains: price numeric (6,2) the user of my program enter price as 555.00 is good. but when he put 555555 it's error, so I need to specify the mask where the mantissa is optional 0 to 999 and the decimal part is programmable 2 or 3 according to choice of the user, I'm using JQuery Masked input plugin and I have not found good regular expression, please, help, I'm working with jsp / servlet.

在测试了我的程序后,我实现了一个软件应用程序管理发票 我注意到以下错误:我在 sqlserver 中的表包含:价格数字 (6,2) 我的程序的用户输入价格为 555.00 是好的。但是当他输入 555555 时它是错误的,所以我需要指定掩码,其中尾数是可选的 0 到 999,小数部分是可编程的 2 或 3,根据用户的选择,我正在使用 JQuery 掩码输入插件,我有没有找到好的正则表达式,请帮忙,我正在使用 jsp/servlet。

回答by LeftyX

You can use jquery numericfor numbers.
The current version does allow what you're looking for but someone has changedthe code a little bit and it works:

您可以将jquery numeric用于数字。
当前版本确实可以满足您的要求,但是有人对代码进行了一些更改,并且可以正常工作:

HTML

HTML

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

Javascript

Javascript

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

This is the whole source.
And I've prepared this fiddleso you can see how it works.

这是整个
我准备了这个小提琴,所以你可以看到它是如何工作的。

回答by Rick

using jQuery input mask plugin (6 whole and 2 decimal places):

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

HTML:

HTML:

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

jQuery:

jQuery:

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

I hope this helps someone

我希望这可以帮助别人

回答by Vladimir Vovk

You can do it using jquery inputmaskplugin.

您可以使用 jquery inputmask插件来完成。

HTML:

HTML:

<input id="price" type="text">

Javascript:

Javascript:

$('#price').inputmask({
  alias: 'numeric', 
  allowMinus: false,  
  digits: 2, 
  max: 999.99
});

https://codepen.io/vladimir-vovk/pen/BgNLgv

https://codepen.io/vladimir-vovk/pen/BgNLgv

回答by Giacomo

or also

或者也

<input type="text" onkeypress="handleNumber(event, ' {-10,3} $')" placeholder="  $" size=25>

with

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
    }
}

回答by ali abolhasani

Use tow function to solve it ,Very simple and useful:

使用tow函数来解决,非常简单实用:

HTML:

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, '');
});

回答by Bikonja

Now that I understand better what you need, here's what I propose. Add a keyup handler for your textbox that checks the textbox contents with this regex ^[0-9]{1,14}\.[0-9]{2}$and if it doesn't match, make the background red or show a text or whatever you like. Here's the code to put in document.ready

现在我更了解您的需求,这就是我的建议。为您的文本框添加一个 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');
        }
    });
});

Here's a JSFiddleof this in action. Also, do the same regex server side and if it doesn't match, the requirements have not been met. You can also do this check the onsubmit event and not let the user submit the page if the regex didn't match.

这是一个JSFiddle的实际操作。另外,做同样的正则表达式服务器端,如果它不匹配,则没有满足要求。您还可以检查 onsubmit 事件,如果正则表达式不匹配,则不允许用户提交页面。

The reason for not enforcing the mask upon text inserting is that it complicates things a lot, e.g. as I mentioned in the comment, the user cannot begin entering the valid input since the beggining of it is not valid. It is possible though, but I suggest this instead.

在文本插入时不强制执行掩码的原因是它使事情复杂化了很多,例如,正如我在评论中提到的,用户无法开始输入有效的输入,因为它的开始是无效的。虽然有可能,但我建议这样做。

回答by uNmAnNeR

Try imaskjs. It has Number, RegExp and other masks. Very simple to extend.

试试imaskjs。它有 Number、RegExp 和其他掩码。扩展非常简单。

回答by Michel Fernandes

If your system is in English, use @Rick answer:

如果您的系统是英文的,请使用@Rick 回答:

If your system is in Brazilian Portuguese, use this:

如果您的系统是巴西葡萄牙语,请使用以下命令:

Import:

进口:

<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:

HTML:

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

JS:

JS:

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

Its because in Brazilian Portuguese we write "1.000.000,00" and not "1,000,000.00" like in English, so if you use "." the system will not understand a decimal mark.

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

It is it, I hope that it help someone. I spend a lot of time to understand it.

就是这样,我希望它可以帮助某人。我花了很多时间来理解它。