Space Lock with REGEX

3

My code for blocking characters looks like this:

 $('#rg').on('keypress', function() {
      var regex = new RegExp("^[ 0-9]+$");
      var _this = this;
      // Curta pausa para esperar colar para completar
      setTimeout( function(){
          var texto = $(_this).val();
          if(!regex.test(texto))
          {
              $(_this).val(texto.substring(0, (texto.length-1)))
          }
      }, 100);
  });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='rg'/>

How do I block SPACE.

Incorrect Example

  

116 416

Should be

  

116416

    
asked by anonymous 02.12.2015 / 17:52

2 answers

1

Your REGEX is almost right, as you just want digits, just remove the REGEX space that will work.

new RegExp("^[0-9]*$")

See the example working:

$('#rg').on('keypress', function() {
  var regex = new RegExp("^[0-9]*$");
  var _this = this;
  setTimeout(function() {
    var texto = $(_this).val();
    if (!regex.test(texto)) {
      $(_this).val(texto.substring(0, (texto.length - 1)))
    }
  }, 100);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='rg' />
    
02.12.2015 / 18:10
1

The problem is the space of your regex. should be like this: RegExp("^[0-9]+$") .

Example:

 $('#rg').on('keypress', function() {
   var regex = new RegExp("^[0-9]+$");
   var _this = this;
   // Curta pausa para esperar colar para completar
   setTimeout(function() {
     var texto = $(_this).val();
     if (!regex.test(texto)) {
       $(_this).val(texto.substring(0, (texto.length - 1)))
     }
   }, 100);
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script><inputtype="text" id="rg">
    
02.12.2015 / 18:10