Prevent user from pasting special characters

Asked

Viewed 7,855 times

9

I am creating a system in which the user must type in a input the mother’s name with only alphanumeric characters. I am 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;
   }
});
  • 4

    More pleasant in terms of usability is to let paste freely and remove after only what does not serve the field. And take advantage to do what everyone forgets after removing characters: leave the cursor in the correct place of the new string.

3 answers

2

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

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

$(document).ready(function(){
  $('#txtInput').bind("cut copy paste",function(e) {
      e.preventDefault();
  });
});
  • fiddle: http://jsfiddle.net/zd5s60eL/

  • 1

    cool suggestion! I particularly don’t like when the system blocks me to paste. If I have my name on Ctrl+c, for example, I would like to be able to paste what I have in memory.

2

An alternative is, as already said, to prevent the user from pasting. Another would be to use a code that checks for any invalid character in the pasted text and, if any, clear the input, as 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 made based in that reply.

Note: I changed your expression, because it prevents the user from typing spaces (I considered that would be the full name, if not the case, just use the original expression same).

2

It may be frustrating for the user not to have the practicality to paste a word into the input. Or you can paste but the text be "cut" in half (index 0 to the first occurrence of an invalid character in string). Or make the process confusing by having invalid characters overwritten/removed, for example: jo@o after being pasted into the 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 input is wrong. Starting from this solution, you can define the regex in the attribute pattern of input:

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

Simply use Javascript to verify that the input is valid (:valid). A message could also be informed 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>

Browser other questions tagged

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