Manish Gupta
Manish Gupta

Reputation: 4656

How to allow only alphanumeric and underscore on keypress

I want to allow only alphanumeric chars and underscore on keypress. But it is not working. This code is not preventing other keycodes on input.

$('#sku').keypress(function(event) {
    var kcode = event.keyCode;
    if (kcode == 8 || kcode == 9 || kcode == 46 || kcode == 95 || kcode > 47 & kcode < 58 || kcode > 64 & kcode < 91 || kcode > 96 & kcode < 123){
        return true;
    }
    else {
        $.niftyNoty({
            type:"warning",icon:"",title:"Only Alpha Numeric and Underscores are allowed.",container:"floating",timer:5000
        });
        return false;
    }
});

how to correct it?

Upvotes: 1

Views: 2264

Answers (1)

Dmytro Shevchenko
Dmytro Shevchenko

Reputation: 34591

What I did to make it work:

- Fixed the logical operators (& -> &&);
- Grouped the AND-groups with parentheses.

$('#sku').keypress(function(event)
{
    var kcode = event.keyCode;

    if (kcode == 8 ||
        kcode == 9 ||
        kcode == 46 ||
        kcode == 95 ||
        (kcode > 47 && kcode < 58) ||
        (kcode > 64 && kcode < 91) ||
        (kcode > 96 && kcode < 123))
    {
        return true;
    }
    else
    {
        return false;
    }
});

Upvotes: 2

Related Questions