Anusha Honey
Anusha Honey

Reputation: 917

Allow only space, underscore , alphabets and numbers in text box

I have this code which allows all characters in a text box. It allows only alphabets and numbers as first character. Now, how do I allow only space and underscore along with alphabets and numbers? I want code only in jQuery. I found a similar solution over here but it doesn't contain jQuery code. http://jsfiddle.net/fwcfq/39/

    $('#value').bind('keypress', function(e) {
        if($('#value').val().length == 0){
            if (e.which == 32){//space bar
                e.preventDefault();
            }
            var valid = (e.which >= 48 && e.which <= 57) || (e.which >= 65 && e.which     <= 90) || (e.which >= 97 && e.which <= 122);
            if (!valid) {
               e.preventDefault();
            }
        }
    }); 

Upvotes: 0

Views: 5159

Answers (2)

DGS
DGS

Reputation: 6025

This code will do what you want

$('#value').bind('keypress', function (e) {
    if ($('#value').val().length == 0) {
        if (e.which == 32) { //space bar
            e.preventDefault();
        }
        var valid = (e.which >= 48 && e.which <= 57) || (e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122);
        if (!valid) {
            e.preventDefault();
        }
    } else {
        var valid = (e.which >= 48 && e.which <= 57) || (e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122 || e.which == 32 || e.which == 95 || e.which == 8);
        if (!valid) {
            e.preventDefault();
        }
    }
});

Fiddle

This approach assumes you know all keys that you want to accept however. For instance the Enter key will be rejected unless you explicitly allow it.

Upvotes: 1

R. Oosterholt
R. Oosterholt

Reputation: 8080

You could also use one of many jQuery plugins doing the same. Example: http://www.thimbleopensource.com/tutorials-snippets/jquery-plugin-filter-text-input

regex would be: [a-zA-Z _]

Upvotes: 0

Related Questions