limiting a date field to just numbers

0

Currently my fields look like this:

function formatar(mascara, documento) {
  var i = documento.value.length;
  var saida = mascara.substring(0, 1);
  var texto = mascara.substring(i)
  if (texto.substring(0, 1) != saida) {
    documento.value += texto.substring(0, 1);
  }
}
<form class="got" method="GET" action="diar.hist.php" name="troca" onsubmit="return verifica()">
  <input type="text" maxlength="10" placeholder="Data" name="Data_dd" OnKeyPress="formatar('##/##/####', this)" /> &nbsp; &nbsp;&nbsp;
  <button class="css_btn_class" type="submit">Atualizar</button>
</form>

If the user types only the numbers, it completes perfectly with the bars, however if the user types letters or symbols he accepts the same way. I wanted to limit the user to only enter numbers and that it formatted in date format as the same type.

    
asked by anonymous 30.01.2018 / 13:58

1 answer

1

Just add the code below that checks the hexadecimal value of the key pressed, if the value does not match a number it does not enter what was keyboard:

if (event.keyCode < 48 || event.keyCode > 57) {
    event.returnValue = false;
}

Here is an example usage below:

function formatar(mascara, documento) {
  var i = documento.value.length;
  var saida = mascara.substring(0, 1);
  var texto = mascara.substring(i);
  if (event.keyCode < 48 || event.keyCode > 57) {
    event.returnValue = false;
  }
  if (texto.substring(0, 1) != saida) {
    documento.value += texto.substring(0, 1);
  }
}
<form class="got" method="GET" action="diar.hist.php" name="troca" onsubmit="return verifica()">
  <input type="text" maxlength="10" placeholder="Data" name="Data_dd" OnKeyPress="formatar('##/##/####', this)" /> &nbsp; &nbsp;&nbsp;
  <button class="css_btn_class" type="submit">Atualizar</button>
</form>
    
30.01.2018 / 14:19