Block special characters but allow hyphen

0

My code for blocking characters looks like this:

 $('#nome').on('keypress', function() {
      var regex = new RegExp("^[ 0-9a-zA-Zàèìòùáéíóúâêîôûãõ\b]+$");
      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='nome'/>

I want to know if there is any way to block special characters, but allowing the use of hyphen - )

    
asked by anonymous 06.11.2015 / 17:50

2 answers

2

Just make a small change to your regex by allowing this. Your regex would look like this:

RegExp("^[a-zA-Z0-9-Zàèìòùáéíóúâêîôûãõ\b]+$");

example would look like this:

 $('#nome').on('keypress', function() {
      var regex = new RegExp("^[a-zA-Z0-9-Zàèìòùáéíóúâêîôûãõ\b]+$");
      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><inputtype="text" id="nome"/>
    
06.11.2015 / 17:59
3

Add the hyphen as the last class character, so you do not need to escape it:

new RegExp("^[ 0-9a-zA-Zàèìòùáéíóúâêîôûãõ\b-]+$");

Your code only removes the last character from the field, this will be a problem if a text with invalid characters is pasted. The ideal is to remove all invalid characters with a denied class, which begins with a caret (e.g. [^a-z] ).

Another improvement I suggest is using the input event that works best than keypress for cast content.

$(function(){
  var regex = new RegExp('[^ 0-9a-zA-Zàèìòùáéíóúâêîôûãõ\b-]', 'g');
  // repare a flag "g" de global, para substituir todas as ocorrências
  $('input').bind('input', function(){
    $(this).val($(this).val().replace(regex, ''));
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><inputtype="text"/>
    
06.11.2015 / 18:21