2010-05-11 13 views
26

Ho un campo di testo del modulo che voglio consentire solo numeri e lettere in. (Es., No # $ !, ecc ...) C'è un modo per lanciare un errore e impedire che il tasto di stampa emetta effettivamente qualcosa se l'utente tenta di utilizzare qualsiasi carattere diverso da numeri e lettere? Ho cercato di trovare un plugin, ma non ho davvero trovato nulla che fa questo ...jquery - convalida i caratteri su Keypress?

+0

Molto simile a: http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery – ThiefMaster

+0

Questo non impedirà l'inserimento di caratteri non alfanumerici nel menu di scelta rapida (clic-destro e incolla). Prova questo su http://jsfiddle.net/ntywf –

+0

il plug-in che lo fa in modo molto fluido: http://digitalbush.com/projects/masked-input-plugin/ – meo

risposta

34
$('input').keyup(function() { 
    var $th = $(this); 
    $th.val($th.val().replace(/[^a-zA-Z0-9]/g, function(str) { alert('You typed " ' + str + ' ".\n\nPlease use only letters and numbers.'); return ''; })); 
}); 

EDIT:

Ci sono alcune altre buone risposte qui che impedirà l'immissione di dati.

Ho aggiornato il mio poiché volevi anche mostrare un errore. La sostituzione può assumere una funzione anziché una stringa. La funzione viene eseguita e restituisce un valore di sostituzione. Ho aggiunto un alert per mostrare l'errore.

http://jsfiddle.net/ntywf/2/

+1

+1 funziona bene. http://jsfiddle.net/ntywf/ Anche se ho * un sentimento *, l'OP potrebbe volere anche gli spazi. – karim79

+0

@ karim79 - Grazie per aver aggiunto jsfiddle. Dovrei farlo davvero più spesso. – user113716

+0

blocca anche i comandi necessari come le operazioni su, giù freccia, maiusc e ctrl. Come controllarlo. –

10
$('#yourfield').keydown(function(e) { 
    // Check e.keyCode and return false if you want to block the entered character. 
}); 
11

Bene la risposta del patrick rimuove personaggio se è sbagliato, in realtà evitare carattere di essere inserito nel campo Usa

$("#field").keypress(function(e) { 
    // Check if the value of the input is valid 
    if (!valid) 
     e.preventDefault(); 
}); 

In questo modo la lettera non verrà a textarea

0

Si potrebbe provare questa estensione:

jQuery.fn.ForceAlphaNumericOnly = 
function() 
{ 
    return this.each(function() 
    { 
     $(this).keydown(function(e) 
     { 
      var key = e.charCode || e.keyCode || 0; 
      // allow backspace, tab, delete, arrows, letters, numbers and keypad numbers ONLY 
      return (
       key == 8 || 
       key == 9 || 
       key == 46 || 
       (key >= 37 && key <= 40) || 
       (key >= 48 && key <= 57) || 
       (key >= 65 && key <= 90) || 
       (key >= 96 && key <= 105)); 
     }) 
    }) 
}; 

Uso:

$("#yourInput").ForceAlphaNumericOnly(); 
+0

Ho appena pensato a questa soluzione: potrebbe esserci un problema se stai inserendo il testo dal buffer.Se l'utente preme ctrl + v, si aspetta che il suo testo venga inserito nel campo se è valido. Questo approccio potrebbe non essere in grado di gestirlo. Devo testarlo però. – Juriy

0

L'estensione sopra jQuery (ForceAlphaNumericOnly) è buono ma ancora consente le seguenti personaggi attraverso [email protected]#$%^&*()

Sul mio Mac, quando si preme il chiave spostamento (keycode 16) e quindi , entra ! ma il codice di accesso è 49, il codice di accesso per 1.

5

Ho trovato che combinando la convalida su keypress e keyup si ottengono i migliori risultati. Key up è un must se vuoi gestire il testo incollato. È anche un trucco tutto in caso di problemi cross browser che consentono valori non numerici nella tua casella di testo.

$("#ZipCode").keypress(function (event) { 

     var key = event.which || event.keyCode; //use event.which if it's truthy, and default to keyCode otherwise 

     // Allow: backspace, delete, tab, and enter 
     var controlKeys = [8, 9, 13]; 
     //for mozilla these are arrow keys 
     if ($.browser.mozilla) controlKeys = controlKeys.concat([37, 38, 39, 40]); 

     // Ctrl+ anything or one of the conttrolKeys is valid 
     var isControlKey = event.ctrlKey || controlKeys.join(",").match(new RegExp(key)); 

     if (isControlKey) {return;} 

     // stop current key press if it's not a number 
     if (!(48 <= key && key <= 57)) { 
      event.preventDefault(); 
      return; 
     } 
    }); 

$('#ZipCode').keyup(function() { 
    //to allow decimals,use/[^0-9\.]/g 
    var regex = new RegExp(/[^0-9]/g); 
    var containsNonNumeric = this.value.match(regex); 
    if (containsNonNumeric) 
     this.value = this.value.replace(regex, ''); 
}); 
+1

In Chrome su incolla (ctrl-v), la chiave non sembra avere alcun valore per questo.valore, quindi la regex non corrisponde mai. In Firefox osservo che End, Delete, Home, Page Up e Page Down non funzionano nel campo. – peater

0
$(document).ready(function() { 
$('.ipFilter').keydown((e) => { 
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || 
     (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true) || 
      e.keyCode === 67 && (e.ctrlKey === true || e.metaKey === true) || 
      e.keyCode === 86 && (e.ctrlKey === true || e.metaKey === true) || 
      e.keyCode === 82 && (e.ctrlKey === true || e.metaKey === true)) || 
     (e.keyCode >= 35 && e.keyCode <= 40)) { 
      return; 
    } 
    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) { 
     e.preventDefault(); 
    } 
    }); 
}); 
Problemi correlati