I have a form text field that I want to allow only numbers and letters in. (i.e., no #$!, etc...) Is there a way to throw up an error and prevent the keypress from actually outputting anything if the user tries to use any character other than numbers and letters? I've been trying to find a plugin, but haven't really found anything that does this...
-
Very similar to: http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery – ThiefMaster May 11 '10 at 16:43
-
This will not prevent non-alphanumeric characters from being pasted in with the context menu (right-click and paste). Try that on http://jsfiddle.net/ntywf – Janek Bogucki May 11 '10 at 17:01
-
the is a plugin that does that very smoothly: http://digitalbush.com/projects/masked-input-plugin/ – meo May 11 '10 at 17:02
7 Answers
$('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:
There are some other good answers here that will prevent the input from taking place.
I've updated mine since you also wanted to show an error. The replace can take a function instead of a string. The function runs and returns a replacement value. I've added an alert
to show the error.

- 318,772
- 63
- 451
- 440
-
1+1 works nicely. http://jsfiddle.net/ntywf/ Though I have a *feeling* the OP might want spaces to be allowed, too. – karim79 May 11 '10 at 16:48
-
@karim79 - Thanks for adding the jsfiddle. I should really do that more often. – user113716 May 11 '10 at 16:50
-
it blocks necessary commands as up, down arrow, shift and ctrl operations as well. How to control that. – VIVEK MISHRA Jul 30 '15 at 08:55
Well the patrick's answer removes character if it is wrong, to actually prevent character from being inserted into the field use
$("#field").keypress(function(e) {
// Check if the value of the input is valid
if (!valid)
e.preventDefault();
});
This way the letter will not come to textarea

- 5,009
- 8
- 37
- 52
$('#yourfield').keydown(function(e) {
// Check e.keyCode and return false if you want to block the entered character.
});

- 310,957
- 84
- 592
- 636
I found that combining validation on keypress and keyup gives the best results. Key up is a must if you want to handle copy pasted text. It is also a catch all in case of cross browser issues which allow non numeric values into your textbox.
$("#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, '');
});

- 8,090
- 5
- 46
- 51
-
1In Chrome on paste (ctrl-v), keyup does not seem to have any value for this.value so the regex never matches. In Firefox I observe that the End, Delete, Home, Page Up and Page Down do not work in the field. – peater Jun 11 '14 at 21:29
You could try this extension:
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));
})
})
};
Useage:
$("#yourInput").ForceAlphaNumericOnly();

- 47,246
- 16
- 124
- 162
-
I just thought about this solution: there might be a problem if you're inserting the text from buffer. If user presses ctrl+v he expects his text to be inserted into the field if it is valid. This approach might not be able to handle this. Have to test it though. – Juriy May 11 '10 at 17:21
$(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();
}
});
});

- 1
- 1
The above jquery extension (ForceAlphaNumericOnly) is good but still allows the following characters through !@#$%^&*()
On my Mac, when you press the shift key (keycode 16
) and then 1, it enters !
but the keycode is 49
, the keycode for 1
.

- 2,656
- 16
- 25