Mask problem for input type="text"

Asked

Viewed 77 times

0

I’m trying to get the input type="text" only accept numbers and keep the date format as I insert the numbers.

//Exibir no formato de data
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;
		}
	}
}

//Não permite alfabeto
$(function() {
   $('#input2').on('input', function() {
      this.value = this.value
         .replace(/[^\d]/g, '');// numbers and decimals only
   });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Exibir no formato de data</h3>
<input id="input1" type="text" maxlength="10" onkeypress="mascaraData( this, event )" required>

<h3>Não permite alfabeto</h3>
<input id="input2" type="text" maxlength="10" required>

As I already showed in the example, I am able to prevent the insertion of letters, I am also able to format the input as date, the problem is that I am not able to unite the two algorithms, so as to make a single input, which does not allow letters and format in date format.

  • 1

    You will need to perform a rigorous validation because this input accepts 00/00/0000 as the date.

1 answer

1


Try the code below:

//Exibir no formato de data
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;
		}
	}
}

//Não permite alfabeto
$(function() {
   $('#input1, #input2').keypress(function(evt){

 var theEvent = evt || window.event;

  // Handle paste
  if (theEvent.type === 'paste') {
      key = event.clipboardData.getData('text/plain');
  } else {
  // Handle key press
      var key = theEvent.keyCode || theEvent.which;
      key = String.fromCharCode(key);
  }

  //Usei uma expressão regular:

  var regex = /[0-9]|\//;
  if(!regex.test(key) ) {
   evt.preventDefault();
  }
  mascaraData(this,evt);
   });
   
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Exibir no formato de data</h3>
<input id="input1" type="text" maxlength="10"  required>

<h3>Não permite alfabeto</h3>
<input id="input2" type="text" maxlength="10" required>

REFERENCE:
1. https://stackoverflow.com/questions/469357/html-text-input-allow-only-numeric-input

Browser other questions tagged

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