limiting a date field to only numbers

Asked

Viewed 35 times

0

Currently my fields are this way:

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 type only the numbers, it completes perfectly with the bars, however if the user type letters or symbols he accepts in the same way. I wanted to limit the user to type only numbers and format in date format as the same type.

1 answer

1


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

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

Follow an example of use 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>

  • Caraca, perfect, meets what I want, thank you very much @Phelipe

Browser other questions tagged

You are not signed in. Login or sign up in order to post.