Prevent user from pasting special characters

8

I am creating a system in which the user must type in an input the name of the mother with only alphanumeric characters. I'm using the code below that is working, but I noticed a flaw. Even allowing not to enter other special characters, if the user copy and paste another special character it will be inserted into the input.

<input type="text" id="nomeMae">

$('#nomeMae').bind('keypress', function (event) 
{
   var regex = new RegExp("^[0-9a-zA-Z\b]+$");
   var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
   if (!regex.test(key)) 
   {
      event.preventDefault();
      return false;
   }
});
    
asked by anonymous 06.01.2015 / 21:50

3 answers

2

You could veto the user from cutting, copying and pasting the form fields.

The following code shows how to do this using jQuery. Here is a simple example:

$(document).ready(function(){
  $('#txtInput').bind("cut copy paste",function(e) {
      e.preventDefault();
  });
});
    
06.01.2015 / 22:01
2

An alternative is, as they have said, prevent the user from pasting. Another would be to use a code that checks for any invalid characters in the pasted text and, if any, clean input , like the following:

$('#nomeMae').on('paste', function(e) {
    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("")
        }
    }, 100);
});

The code was based on on this answer .

    
07.01.2015 / 01:23
2

It may be frustrating for the user not to have the convenience of pasting a word into input . Or you can paste but the text will be "cut" in half ( index 0 until the first occurrence of an invalid character in string ). Or make the process confusing when having the invalid characters replaced / removed, for example: jo @ o after being pasted into input would appear joo (probably after about three attempts to paste the user would realize that the problem is the character @ ).

Perhaps a better solution is to warn you that the entry is wrong. From this solution, you can set the regex attribute in pattern of input :

<input class='nome-mae' type='text' pattern='^[ 0-9a-zA-Z\b]+$'/>

Just use Javascript to check that input is valid ( :valid ). You could also be told a message to let him know what was done wrong. Here is a possible alternative:

$(function(){
  $('.nome-mae').on('blur keydown keyup keypress paste', function(){
     setAlertMessage( $(this).is(':valid') ? 
         "" : 
         "Este campo não pode conter caracteres especiais.");
  });
               
  function setAlertMessage(message){
     $('.message').html(message);
  }
});
input {
  border: 2px solid #ccc;
  padding: 6px;
  width: 300px
}


/*
 * será aplicado automaticamente quando
 * o input for invalido */
input:invalid {
  box-shadow: none;
  border-color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>

<input class='nome-mae' type='text' pattern='^[ 0-9a-zA-Z\b]+$' placeholder='Nome da Mãe'/>
<p class='message'></p>
    
07.01.2015 / 03:04