¿Cómo puedo bloquear o restringir el carácter especial de los campos de entrada con jQuery?

StackOverflow https://stackoverflow.com/questions/895659

Pregunta

¿Cómo bloqueo los caracteres especiales de ser escrito en un campo de entrada con jQuery?

No hay solución correcta

Otros consejos

Un ejemplo simple que utiliza una expresión regular que se podía cambiar para permitir / denegar lo que quiera.

$('input').on('keypress', function (event) {
    var regex = new RegExp("^[a-zA-Z0-9]+$");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
       event.preventDefault();
       return false;
    }
});

Yo estaba buscando una respuesta que restringe la entrada a sólo caracteres alfanuméricos, pero todavía se permite el uso de caracteres de control (por ejemplo, la tecla de retroceso, suprimir, la lengüeta) y copia + pega. Ninguna de las respuestas proporcionadas que he intentado satisfecho con todos estos requisitos, por lo que se me ocurrió lo siguiente utilizando el evento input.

$('input').on('input', function() {
  $(this).val($(this).val().replace(/[^a-z0-9]/gi, ''));
});

Editar
Como rinogo señaló en los comentarios, el fragmento de código anterior hace que el cursor hasta el final de la entrada al escribir en el medio del texto de entrada. Creo que el siguiente fragmento de código resuelve este problema.

$('input').on('input', function() {
  var c = this.selectionStart,
      r = /[^a-z0-9]/gi,
      v = $(this).val();
  if(r.test(v)) {
    $(this).val(v.replace(r, ''));
    c--;
  }
  this.setSelectionRange(c, c);
});

Respuesta corta: evitar que el evento 'pulsación de tecla':

$("input").keypress(function(e){
    var charCode = !e.charCode ? e.which : e.charCode;

    if(/* Test for special character */ )
        e.preventDefault();
})

Respuesta larga: Usar un plugin como jquery.alphanum

Hay varias cosas a considerar al elegir una solución:

  • texto pegado
  • Los caracteres de control como tecla de retroceso o F5 pueden prevenirse por el código de seguridad.
  • e, i, etc ä
  • árabe o chino ...
  • Compatibilidad del navegador de la Cruz

Creo que esta área es lo suficientemente compleja como para justificar el uso de un tercero plug-in del partido. Probé varios de los plugins disponibles, pero encontré algunos problemas con cada uno de ellos, así que fui por delante y escribió jquery.alphanum . El código es el siguiente:

$("input").alphanum();

O para un mayor control de grano fino, añadir algunos ajustes:

$("#username").alphanum({
    allow      : "€$£",
    disallow   : "xyz",
    allowUpper : false
});

Espero que ayuda.

Utilice atributo de entrada patrón de HTML5!

<input type="text" pattern="^[a-zA-Z0-9]+$" />

Tome una mirada en el plugin de jQuery alfanumérica. https://github.com/KevinSheedy/jquery.alphanum

//All of these are from their demo page
//only numbers and alpha characters
$('.sample1').alphanumeric();
//only numeric
$('.sample4').numeric();
//only numeric and the .
$('.sample5').numeric({allow:"."});
//all alphanumeric except the . 1 and a
$('.sample6').alphanumeric({ichars:'.1a'});

Usar expresiones regulares para permitir / denegar cualquier cosa. Además, para una versión ligeramente más robusto que la respuesta aceptada, permitiendo a los personajes que no tienen un valor de clave asociado con ellos (retroceso, pestaña, teclas de flecha, borrar, etc.) se puede hacer pasando primero a través de la pulsación de tecla y eventos comprobar la clave basada en código clave en lugar de valor.

$('#input').bind('keydown', function (event) {
        switch (event.keyCode) {
            case 8:  // Backspace
            case 9:  // Tab
            case 13: // Enter
            case 37: // Left
            case 38: // Up
            case 39: // Right
            case 40: // Down
            break;
            default:
            var regex = new RegExp("^[a-zA-Z0-9.,/ $@()]+$");
            var key = event.key;
            if (!regex.test(key)) {
                event.preventDefault();
                return false;
            }
            break;
        }
});

Su caja de texto:

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

Su javascript:

$("#name").keypress(function(event) {
    var character = String.fromCharCode(event.keyCode);
    return isValid(character);     
});

function isValid(str) {
    return !/[~`!@#$%\^&*()+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}

Escribir un código javascript en caso onkeypress del cuadro de texto. según el requisito de permitir y restringir el personaje en su cuadro de texto

function isNumberKeyWithStar(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 42)
        return false;
    return true;
}
function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}
function isNumberKeyForAmount(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
        return false;
    return true;
}

Yo uso este código de modificación de otros que he visto. Sólo gran a la escritura del usuario si la tecla presionada o texto pegado pasa la prueba patrón (partido) (este ejemplo es una entrada de texto que sólo permite a 8 dígitos)

$("input").on("keypress paste", function(e){
    var c = this.selectionStart, v = $(this).val();
    if (e.type == "keypress")
        var key = String.fromCharCode(!e.charCode ? e.which : e.charCode)
    else
        var key = e.originalEvent.clipboardData.getData('Text')
    var val = v.substr(0, c) + key + v.substr(c, v.length)
    if (!val.match(/\d{0,8}/) || val.match(/\d{0,8}/).toString() != val) {
        e.preventDefault()
        return false
    }
})

Este es un ejemplo que impide que el usuario escribiendo el carácter "a"

$(function() {
$('input:text').keydown(function(e) {
if(e.keyCode==65)
    return false;

});
});

Los códigos clave refrence aquí: Read http://www.expandinghead.net/keycode.html

Sí se puede hacer mediante el uso de jQuery como:

<script>
$(document).ready(function()
{
    $("#username").blur(function()
    {
        //remove all the class add the messagebox classes and start fading
        $("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
        //check the username exists or not from ajax
        $.post("user_availability.php",{ user_name:$(this).val() } ,function(data)
        {
          if(data=='empty') // if username is empty
          {
            $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
            { 
              //add message and change the class of the box and start fading
              $(this).html('Empty user id is not allowed').addClass('messageboxerror').fadeTo(900,1);
            });
          }
          else if(data=='invalid') // if special characters used in username
          {
            $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
            { 
              //add message and change the class of the box and start fading
              $(this).html('Sorry, only letters (a-z), numbers (0-9), and periods (.) are allowed.').addClass('messageboxerror').fadeTo(900,1);
            });
          }
          else if(data=='no') // if username not avaiable
          {
            $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
            { 
              //add message and change the class of the box and start fading
              $(this).html('User id already exists').addClass('messageboxerror').fadeTo(900,1);
            });     
          }
          else
          {
            $("#msgbox").fadeTo(200,0.1,function()  //start fading the messagebox
            { 
              //add message and change the class of the box and start fading
              $(this).html('User id available to register').addClass('messageboxok').fadeTo(900,1); 
            });
          }

        });

    });
});
</script>
<input type="text" id="username" name="username"/><span id="msgbox" style="display:none"></span>

y el guión para su user_availability.php será:

<?php
include'includes/config.php';

//value got from the get method
$user_name = trim($_POST['user_name']);

if($user_name == ''){
    echo "empty";
}elseif(preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $user_name)){
    echo "invalid";
}else{
    $select = mysql_query("SELECT user_id FROM staff");

    $i=0;
    //this varible contains the array of existing users
    while($fetch = mysql_fetch_array($select)){
        $existing_users[$i] = $fetch['user_id'];
        $i++;
    }

    //checking weather user exists or not in $existing_users array
    if (in_array($user_name, $existing_users))
    {
        //user name is not availble
        echo "no";
    } 
    else
    {
        //user name is available
        echo "yes";
    }
}
?>

He intentado añadir / y \ , pero no tenido éxito.


También puede hacerlo mediante el uso de JavaScript y código será:

<!-- Check special characters in username start -->
<script language="javascript" type="text/javascript">
function check(e) {
    var keynum
    var keychar
    var numcheck
    // For Internet Explorer
    if (window.event) {
        keynum = e.keyCode;
    }
    // For Netscape/Firefox/Opera
    else if (e.which) {
        keynum = e.which;
    }
    keychar = String.fromCharCode(keynum);
    //List of special characters you want to restrict
    if (keychar == "'" || keychar == "`" || keychar =="!" || keychar =="@" || keychar =="#" || keychar =="$" || keychar =="%" || keychar =="^" || keychar =="&" || keychar =="*" || keychar =="(" || keychar ==")" || keychar =="-" || keychar =="_" || keychar =="+" || keychar =="=" || keychar =="/" || keychar =="~" || keychar =="<" || keychar ==">" || keychar =="," || keychar ==";" || keychar ==":" || keychar =="|" || keychar =="?" || keychar =="{" || keychar =="}" || keychar =="[" || keychar =="]" || keychar =="¬" || keychar =="£" || keychar =='"' || keychar =="\\") {
        return false;
    } else {
        return true;
    }
}
</script>
<!-- Check special characters in username end -->

<!-- in your form -->
    User id : <input type="text" id="txtname" name="txtname" onkeypress="return check(event)"/>

sólo los números:

  

$ ( 'input.time'). Keydown (function (e) {if (e.keyCode> = 48 &&   e.keyCode <= 57) {       return true; } Else {       falso retorno; }});

o por el tiempo que incluye ":"

  

$ ( 'input.time'). Keydown (function (e) {if (e.keyCode> = 48 &&   e.keyCode <= 58) {       return true; } Else {       falso retorno; }});

incluyendo también eliminar y retroceso:

  

$ ( 'input.time'). Keydown (function (e) {if ((e.keyCode> = 46 &&   e.keyCode <= 58) || e.keyCode == 8) {return true; } Else {             falso retorno; }});

unfortuneatly no tener que trabajar en un iMAC

Se busca a comentar sobre el comentario de Alex a la respuesta de Dale. No es posible (primero tendrá la cantidad de "representante"? Eso suele suceder muy pronto .. extraño sistema). Así como una respuesta:

Retroceso se puede añadir mediante la adición de \ b a la definición de expresiones regulares como esto: [a-zA-Z0-9 \ b]. O simplemente permite que toda la gama de América, entre ellos más o menos nada caracteres "no exóticas" (también controlan caracteres como la tecla de retroceso): ^ [\ u0000- \ u024F \ u20AC] + $

La única verdadera carbón Unicode fuera de América no es el símbolo del euro (20ac), añadir lo que puede necesitar más.

Para manejar también de entrada introduce a través de copiar y pegar, simplemente también se unen al evento "cambio" y compruebe la entrada allí también - eliminarlo o la creación de bandas que / que da un mensaje de error como "caracteres que no son compatibles" ..

if (!regex.test($j(this).val())) {
  alert('your input contained not supported characters');
  $j(this).val('');
  return false;
}

Restringir caracteres especiales al pulsar las teclas. Aquí hay una página de prueba para los códigos clave: http://www.asquare.net/javascript/tests /KeyCode.html

var specialChars = [62,33,36,64,35,37,94,38,42,40,41];

some_element.bind("keypress", function(event) {
// prevent if in array
   if($.inArray(event.which,specialChars) != -1) {
       event.preventDefault();
   }
});

En angular, que necesitaba un formato de moneda adecuada en mi campo de texto. Mi solución:

var angularApp = angular.module('Application', []);

...

// new angular directive
angularApp.directive('onlyNum', function() {
    return function( scope, element, attrs) {

        var specialChars = [62,33,36,64,35,37,94,38,42,40,41];

        // prevent these special characters
        element.bind("keypress", function(event) {
            if($.inArray(event.which,specialChars) != -1) {
                prevent( scope, event, attrs)
             }
        });

        var allowableKeys = [8,9,37,39,46,48,49,50,51,52,53,54,55,56
            ,57,96,97,98,99,100,101,102,103,104,105,110,190];

        element.bind("keydown", function(event) {
            if($.inArray(event.which,allowableKeys) == -1) {
                prevent( scope, event, attrs)
            }
        });
    };
})

// scope.$apply makes angular aware of your changes
function prevent( scope, event, attrs) {
    scope.$apply(function(){
        scope.$eval(attrs.onlyNum);
        event.preventDefault();
    });
    event.preventDefault();
}

En el html añadir la directiva

<input only-num type="text" maxlength="10" id="amount" placeholder="$XXXX.XX"
   autocomplete="off" ng-model="vm.amount" ng-change="vm.updateRequest()">

y en el controlador angular correspondiente I sólo permiten que haya solamente 1 período, convertir el texto en número y agregar el número de redondeo en 'desenfoque'

...

this.updateRequest = function() {
    amount = $scope.amount;
    if (amount != undefined) {
        document.getElementById('spcf').onkeypress = function (e) {
        // only allow one period in currency
        if (e.keyCode === 46 && this.value.split('.').length === 2) {
            return false;
        }
    }
    // Remove "." When Last Character and round the number on blur
    $("#amount").on("blur", function() {
      if (this.value.charAt(this.value.length-1) == ".") {
          this.value.replace(".","");
          $("#amount").val(this.value);
      }
      var num = parseFloat(this.value);
      // check for 'NaN' if its safe continue
      if (!isNaN(num)) {
        var num = (Math.round(parseFloat(this.value) * 100) / 100).toFixed(2);
        $("#amount").val(num);
      }
    });
    this.data.amountRequested = Math.round(parseFloat(amount) * 100) / 100;
}

...

Para reemplazar caracteres especiales, espacio y convertir a minúsculas

$(document).ready(function (){
  $(document).on("keyup", "#Id", function () {
  $("#Id").val($("#Id").val().replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '').toLowerCase());
 }); 
});
[User below code to restrict special character also    

$(h.txtAmount).keydown(function (event) {
        if (event.shiftKey) {
            event.preventDefault();
        }
        if (event.keyCode == 46 || event.keyCode == 8) {
        }
        else {
            if (event.keyCode < 95) {
                if (event.keyCode < 48 || event.keyCode > 57) {
                    event.preventDefault();
                }
            }
            else {
                if (event.keyCode < 96 || event.keyCode > 105) {
                    event.preventDefault();
                }
            }
        }


    });]
$(function(){
      $('input').keyup(function(){
        var input_val = $(this).val();
        var inputRGEX = /^[a-zA-Z0-9]*$/;
        var inputResult = inputRGEX.test(input_val);
          if(!(inputResult))
          {     
            this.value = this.value.replace(/[^a-z0-9\s]/gi, '');
          }
       });
    });
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top