jQuery Input Mask Decimal point

Codious-JR picture Codious-JR · Aug 27, 2014 · Viewed 21.8k times · Source

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?

Answer

Rohan Kumar picture Rohan Kumar · Aug 27, 2014

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