Numeric mask for date field in Javascript

Asked

Viewed 32,357 times

0

I created a Data field and with the Javascript function I’m masking it for date, but how to use only numbers and not text?

function mascaraData( campo, e )
{
	var kC = (document.all) ? event.keyCode : e.keyCode;
	var data = campo.value;
	
	if( kC!=8 && kC!=46 )
	{
		if( data.length==2 )
		{
			campo.value = data += '/';
		}
		else if( data.length==5 )
		{
			campo.value = data += '/';
		}
		else
			campo.value = data;
	}
}
<html>
<head>
<title>Mascara data formulario</title>

</head>
<body>
	<form>
		<input type="text" name="outra_data" id="outra_data" maxlength="10" onkeypress="mascaraData( this, event )" />
	</form>

</body>
</html>

2 answers

4

I found this functional example, validates both the date in the dd/mm/yyyy format and does not allow characters other than numbers, just adapt your input for the function, thus:

function mascaraData(val) {
  var pass = val.value;
  var expr = /[0123456789]/;

  for (i = 0; i < pass.length; i++) {
    // charAt -> retorna o caractere posicionado no índice especificado
    var lchar = val.value.charAt(i);
    var nchar = val.value.charAt(i + 1);

    if (i == 0) {
      // search -> retorna um valor inteiro, indicando a posição do inicio da primeira
      // ocorrência de expReg dentro de instStr. Se nenhuma ocorrencia for encontrada o método retornara -1
      // instStr.search(expReg);
      if ((lchar.search(expr) != 0) || (lchar > 3)) {
        val.value = "";
      }

    } else if (i == 1) {

      if (lchar.search(expr) != 0) {
        // substring(indice1,indice2)
        // indice1, indice2 -> será usado para delimitar a string
        var tst1 = val.value.substring(0, (i));
        val.value = tst1;
        continue;
      }

      if ((nchar != '/') && (nchar != '')) {
        var tst1 = val.value.substring(0, (i) + 1);

        if (nchar.search(expr) != 0)
          var tst2 = val.value.substring(i + 2, pass.length);
        else
          var tst2 = val.value.substring(i + 1, pass.length);

        val.value = tst1 + '/' + tst2;
      }

    } else if (i == 4) {

      if (lchar.search(expr) != 0) {
        var tst1 = val.value.substring(0, (i));
        val.value = tst1;
        continue;
      }

      if ((nchar != '/') && (nchar != '')) {
        var tst1 = val.value.substring(0, (i) + 1);

        if (nchar.search(expr) != 0)
          var tst2 = val.value.substring(i + 2, pass.length);
        else
          var tst2 = val.value.substring(i + 1, pass.length);

        val.value = tst1 + '/' + tst2;
      }
    }

    if (i >= 6) {
      if (lchar.search(expr) != 0) {
        var tst1 = val.value.substring(0, (i));
        val.value = tst1;
      }
    }
  }

  if (pass.length > 10)
    val.value = val.value.substring(0, 10);
  return true;
}
<input type="text" name="outra_data" id="outra_data" maxlength="10" onkeypress="mascaraData(this)" />

Code reference:

http://forum.imasters.com.br/topic/256533-fazer-mascara-para-text-field-para-ddmmaaaa/

  • I used this @Articuno function, but I wiped it down because some features I didn’t use and preferred to use HTML attributes

1

Uses jQuery. Must meet what you want.

    <script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.min.js"></script>
    <SCRIPT language="javascript">
     $(document).ready(function () {
        $('#outra_data').mask('99/99/9999');
        return false;
    });
    </SCRIPT>
  • So I need to use javascript only.

  • The code I sent you is javascript.

  • I think he meant pure javascript, no framework.

  • this I’m looking for some solution or tip for Pure Javascript without Framework.

  • Andre, my good, jQuery is a separate universe in [so] and [en.so], if the question only has the tag [tag:javascript], we should respond in pure JS and add a framework option if we think it leaves the answer wider. Anyway, just a couple of tips...

  • @Brasofilo, my answer was to try to help. Many turn to stackoverflow when they’re on the ropes so if you offer options for the solution, you can at least anticipate a solution that allows the software to go into production. I get your comment.

Show 1 more comment

Browser other questions tagged

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