Mascara Javascript

0

Good afternoon guys, I need your help.

I need a mask for a field number in my system where the user can enter from 0.0 to 130.00 if the value is greater than 130 it will only accept 999.99.

Could anyone help me?

    
asked by anonymous 18.12.2017 / 20:46

1 answer

2

Just apply maxlength by counting all characters in 999,99 , which in this case would be 6 , basically would give maxlength to almost any mask you find.

Of course some jQuery and related plugins already have configuration for this, but they are exceptions.

Examples of money masks / money that exist on the site:

With jQuery:

$("#meuDinheiro").maskMoney();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://plentz.github.io/jquery-maskmoney/javascripts/jquery.maskMoney.min.js"></script>

<input type="text" id="meuDinheiro" data-thousands="." data-decimal="," data-prefix="" maxlength="6" />

Now if you want to turn 999,99 you can limit to 7 and apply keyup

$("#meuDinheiro").maskMoney().on("keyup", function () {
   if (this.value.length > 6) {
       this.value = "999,99";
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://plentz.github.io/jquery-maskmoney/javascripts/jquery.maskMoney.min.js"></script>

<input type="text" id="meuDinheiro" data-thousands="." data-decimal="," data-prefix="" maxlength="7" />

No jQuery (JavaScript and Regex)

Reply: link

function formatarMoeda() {
  var elemento = document.getElementById('valor');
  var valor = elemento.value;
  
  valor = valor + '';
  valor = parseInt(valor.replace(/[\D]+/g,''));

  if (!isNaN(valor)) {
    valor = valor + '';
    valor = valor.replace(/([0-9]{2})$/g, ",$1");

    if (valor.length > 6) {
        valor = valor.replace(/([0-9]{3}),([0-9]{2}$)/g, ".$1,$2");
    }
  } else {
     valor = '';
  }

  elemento.value = valor;
}
<input type="text" id="valor" onkeyup="formatarMoeda();" maxlength="6" />

Now if you want to turn 999,99 you can limit to 7 and apply keyup

function formatarMoeda() {
  var elemento = document.getElementById('valor');
  var valor = elemento.value;
  
  valor = valor + '';
  valor = parseInt(valor.replace(/[\D]+/g,''));

  if (!isNaN(valor)) {
    valor = valor + '';
    valor = valor.replace(/([0-9]{2})$/g, ",$1");

    if (valor.length > 6) {
        valor = '999,99'; //Mudei esta linha
    }
  } else {
     valor = '';
  }

  elemento.value = valor;
}
<input type="text" id="valor" onkeyup="formatarMoeda();" maxlength="7" />
    
18.12.2017 / 21:00