jQuery Input Mask Decimal point

2019-05-19 08:33发布

问题:

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"]});