Skip to content

Instantly share code, notes, and snippets.

@brendomaciel
Last active June 8, 2022 18:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brendomaciel/c7aef1d4d5f96ae3833b1cb592e49b36 to your computer and use it in GitHub Desktop.
Save brendomaciel/c7aef1d4d5f96ae3833b1cb592e49b36 to your computer and use it in GitHub Desktop.
Máscara de porcentagem utilizando o plugin jQuery Mask Plugin (limita o valor máximo a 100)
$('#percent').mask('P', {
translation: {
'P': {
pattern: /[\d\.,]/,
recursive: true
}
},
onKeyPress: function(val, e, field, options) {
var old_value = $(field).data('oldValue') || '';
val = val.trim();
val = val.replace(',', '.');
val = val.length > 0 ? val : '0';
// Transformando múltiplos pontos em um único ponto
val = val.replace(/[\.]+/, '.');
// Verificando se o valor contém mais de uma ocorrência de ponto
var dot_occurrences = (val.match(/\./g) || []).length > 1;
// Verificando se o valor está de acordo com a sintaxe do float
var is_float = /[-+]?[\d]*\.?[\d]+/.test(val);
if (dot_occurrences || !is_float) {
val = old_value;
}
// Força o valor a ficar no intervalo de 0 à 100
val = parseFloat(val) >= 100 ? '100' : val;
val = parseFloat(val) < 0 ? '0' : val;
$(field)
.val(val)
.data('oldValue', val);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment