como faço para bloquear ou restringir caracteres especiais a partir de campos de entrada com jQuery?

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

Pergunta

Como faço para bloquear caracteres especiais de ser digitado em um campo de entrada com jQuery?

Nenhuma solução correta

Outras dicas

Um exemplo simples usando uma expressão regular que você poderia mudar para permitir / disallow que quiser.

$('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;
    }
});

Eu estava procurando uma resposta que a entrada restrito a apenas caracteres alfanuméricos, mas ainda permitido o uso de caracteres de controle (por exemplo, de retrocesso, de exclusão, de tabulação) e copiar + colar. Nenhuma das respostas, desde que eu tentei satisfeitos todos estes requisitos, então eu vim com o seguinte usando o evento input.

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

Editar:
Como rinogo apontou nos comentários, o trecho de código forças acima do cursor até o fim da entrada quando digitação no meio do texto de entrada. Eu acredito que o trecho de código abaixo resolve 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);
});

Resposta curta: impedir que o evento 'keypress':

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

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

Resposta longa: Use um plugin como jquery.alphanum

Há várias coisas a considerar ao escolher uma solução:

  • Texto colado
  • caracteres de controlo como de retrocesso ou F5 pode ser impedida pelo código de cima.
  • E, eu, etc
  • árabe ou chinês ...
  • compatibilidade cross-browser

Eu acho que essa área é bastante complexo para mandado usando um 3o partido plugin. Eu tentei vários dos plugins disponíveis, mas encontrou alguns problemas com cada um deles, então eu fui em frente e escreveu jquery.alphanum . Os olhares código como este:

$("input").alphanum();

Ou para mais controle de grão fino, adicione algumas configurações:

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

Hope isso ajuda.

atributo de entrada padrão de Uso HTML5!

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

Dê uma olhada o plugin jQuery alfanumérico. 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'});

Use Regex para permitir / disallow qualquer coisa. Além disso, para uma versão ligeiramente mais robusto do que a resposta aceita, permitindo personagens que não têm um valor de chave associado a eles (retrocesso, tabulação, setas, apagar, etc.) pode ser feito por primeira passagem através do evento keypress e verificar a chave com base no código de acesso, em vez 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;
        }
});

A sua caixa de texto:

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

Seu javascript:

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

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

escrever algum código javascript no evento onkeypress de caixa de texto. como pela exigência permitir e restringir o personagem em sua caixa 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;
}

Eu uso este código modificar outros que eu vi. Apenas grande para a escrita do usuário, se a tecla pressionada ou texto colado passar no teste padrão (jogo) (neste exemplo, é uma entrada de texto que permite apenas 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 é um exemplo que impedir que o usuário digitar o caractere "a"

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

});
});

Os códigos de chave refrence aqui:
http://www.expandinghead.net/keycode.html

Sim, você pode fazer usando 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>

e roteiro para o seu 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";
    }
}
?>

Eu tentei adicionar para / e \ , mas não teve sucesso.


Você também pode fazê-lo usando javascript e 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)"/>

apenas os números:

$ ( 'input.time'). Keydown (function (e) {if (e.KeyCode> = 48 && e.KeyCode <= 57) { return true; } outro { retorna falso; }});

ou para o tempo, incluindo ":"

$ ( 'input.time'). Keydown (function (e) {if (e.KeyCode> = 48 && e.KeyCode <= 58) { return true; } outro { retorna falso; }});

incluindo também apagar e backspace:

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

unfortuneatly não fazê-la funcionar em um iMac

queria comentar sobre o comentário de Alex para a resposta de Dale. Não é possível (primeira necessidade quanto "representante"? Isso não vai acontecer muito em breve .. estranho sistema.) Assim como resposta:

Backspace pode ser adicionado, adicionando \ b para a definição regex como esta: [a-zA-Z0-9 \ b]. Ou você simplesmente permitir que toda a gama Latina, incluindo mais ou menos qualquer coisa "não exóticas" caracteres (também controlar caracteres como backspace): ^ [\ u0000- \ u024F \ u20AC] + $

Apenas real caractere unicode fora Latina há o símbolo do euro (20ac), adicionar o que você pode precisar de mais.

Para também manipular a entrada introduzido através de copiar e colar, simplesmente também se ligam ao evento "mudança" e verificar a entrada lá também - excluí-lo ou distribuição it / dando uma mensagem de erro como "caracteres não suportados" ..

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

Restringir especiais caracteres na tecla. Aqui está uma página de teste para os códigos-chave: 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();
   }
});

Em Angular, eu precisava de um formato de moeda adequada no meu campo de texto. Minha solução:

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();
}

No html adicionar a diretiva

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

e no controlador angular correspondente Eu só permitem que haja apenas 1 período, texto convertido ao número e número add arredondamento em 'borrão'

...

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 substituir caracteres especiais, espaço e converter para 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 em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top