views:

617

answers:

4

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...

+3  A: 
$('#yourfield').keydown(function(e) {
    // Check e.keyCode and return false if you want to block the entered character.
});
ThiefMaster
+5  A: 
$('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.

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

patrick dw
+1 works nicely. http://jsfiddle.net/ntywf/ Though I have a *feeling* the OP might want spaces to be allowed, too.
karim79
@karim79 - Thanks for adding the jsfiddle. I should really do that more often.
patrick dw
+1  A: 

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

Juriy
+1  A: 

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