jQuery Input Mask Decimal point

我们两清 提交于 2019-12-22 14:55:44

问题


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,

I need the following to be valid:

      10
      150
      12.25
      0.45

At the moment I am doing:

$('#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:

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)

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?


回答1:


Try to use the optional parmaneter greedy like,

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

Read 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
        }
    });
});

Demo

Or simply use toggleClass like,

$(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" />



回答2:


Have you tried using multiple masks?

$('#from_id').inputmask({'mask':["9{0,5}.9{0,2}", "999"]});


来源:https://stackoverflow.com/questions/25526436/jquery-input-mask-decimal-point

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!