Keyup allow to contain only one point between the characters typed in input

5

Example output:

000.000000
1.000
99.9.99.999 // <- error não pode ter mais de 1 ponto

Code:

$('input').keyup(function(e){
  $(this).val(function() {
    var val = this.value;
    return val.replace(/(\.)+/g, function(char, str) {
      return str;
    });
  });
});

JSFIDDLE

    
asked by anonymous 03.12.2015 / 00:24

3 answers

2

I created a function called validaPontos() which returns the number of points that are in the field. after this is to compare if it is greater than or equal to two and if it is to remove the character.

Example:

$('input').keyup(function(e) {
  var valor = this.value;
  var pattern = /\.(?=[^.]*$)/;
  if (validaPontos(valor) >= 2) {
    this.value = valor.replace(pattern, "");
  }
});

function validaPontos(valor) {
  var quantidadeDePontos = 0;
  for (var i = 0; i < valor.length; i++) {
    if (valor[i] === '.') {
      quantidadeDePontos++;
    }
  }
  return quantidadeDePontos;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script><inputtype="text" />

Updated If the user tries to enter a dot in the middle, the last point of the string will be removed!

Or you can also use a plugin for these validations: MaskMoney

Example Usage:

$('#currency').maskMoney();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery-maskmoney/3.0.2/jquery.maskMoney.min.js"></script>


<input type="text" id="currency" />
    
03.12.2015 / 02:27
1

I achieved a more "compact" mode similar to that of @GabrielRodrigues

$('input').keyup(function(e) {
  $(this).val(function() {
    var val = this.value;
    if (val.split('.').length > 2) val = val.replace(/\.+$/, '');
    return val;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script><inputtype="text" />
    
03.12.2015 / 12:31
1

Well ... that gave me some work, but I think I finally got something quite interesting. Look:

With the existence of a point, if you try to add another one after this you will not be able to, so the point should be deleted. Instead of onKey , I used onInput , which will detect if something is changed, so that the user can "navigate" the lestras without being played to the end of input , besides the performance question, because in that if it is imperceptible to delete the point.

$('input').on("input", function(){
  var val = this.value;
  var test = /^[^.]?.[^.]*$/;
  if(test.test(val)){
    return;
  }else{
    var n = val.search(/\./);
    var beforeDot = val.substring(0, n);
    var dot = val.substring(n, n+1);
    var afterDot = val.substring(n+1, val.length);
    $(this).val(beforeDot.replace(/\./g, "") + dot + afterDot.replace(/\./g, ""));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><inputtype="text" />
    
03.12.2015 / 01:48