jQuery输入掩码小数点 [英] jQuery Input Mask Decimal point

查看:115
本文介绍了jQuery输入掩码小数点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 https://github.com/RobinHerbots/jquery.inputmask ,但我似乎无法导出与整数&相对应的模式.十进制.例如

I am using the jQuery plugin found at https://github.com/RobinHerbots/jquery.inputmask but I can't seem to be able to derive a pattern that corresponds to a integer & a decimal. For example,

我需要以下内容有效:

      10
      150
      12.25
      0.45

此刻我正在做

$('#from_id').inputmask("9{0,5}.9{0,2}");

但这意味着如果用户未指定小数点后的内容,则输出为:

But this means that if the user does not specify what comes after the decimal point, the resulting output is:

例如,如果用户只想输入12(并且他没有指定小数点),则输出为

For example, if the user only wants to input 12 (and he does not specify the decimal point) the output is

12___.__

(因为掩码正在等待小数点)

(as the mask is waiting for the decimal point)

但是,如果用户指定小数点,例如12.00,则输出如下所示:

But if the user specifies the decimal point, for example 12.00, The output is fine like:

12.00 

有人可以帮助我解决这个问题吗?

Could someone help me with this problem?

推荐答案

尝试使用可选的parmaneter greedy之类的

Try to use the optional parmaneter greedy like,

$('#from_id').inputmask({'mask':"9{0,5}.9{0,2}", greedy: false});

阅读 optional-masks-with-greedy-false

您可以验证上述遮罩.或使用您自己的逻辑来进行验证,

You can validate above mask. Or use your own logica to validate like,

$(function(){
    $('#id').on('keyup', function(e) {
        if (!this.value.match(/^\d{0,5}(\.[0-9]{1,2})?$/)) {
            $(this).addClass('error');// adding error class
        } else {
            $(this).removeClass('error');// remove error class
        }
    });
});

演示

或者只需使用 toggleClass 之类的

$(function() {
  $('#id').on('keyup', function(e) {
    $(this).toggleClass('error', !this.value.match(/^\d{0,5}(\.[0-9]{1,2})?$/));
  });
});

.error {
  color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="id" />

这篇关于jQuery输入掩码小数点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆