fightstarr20
fightstarr20

Reputation: 12608

jQuery restrict characters that can be entered into input

I have the following jquery which forces characters entered into an input box into uppercase.

jQuery(document).ready(function() {
    jQuery('.uppercase').keyup(function()
    {
        jQuery(this).val(jQuery(this).val().toUpperCase());
    });
});

I want to restrict input so that only english alpha-numeric characters can be entered. What's the best way of tackling this?

Upvotes: 0

Views: 843

Answers (2)

Christos Lytras
Christos Lytras

Reputation: 37318

A very simple way to do what you want, is to catch the keydown event, then check the key ASCII code. If it's not between 0x30 (ASCII '0') and 0x39 (ASCII '9') and it's not between 0x41 (ASCII 'A') and 0x7a (ASCII 'z'), then you just cancel the event by calling event.preventDefault. You can also prevent user by typing lowercase characters, if you change the last ASCII check from lower 'z' (0x7a) to upper 'Z' (0x5a). Also you can have CSS text-transform: uppercase; so the user does not see the transition between lower and upper conversion.

jQuery('#test').on('keydown', function(e) {
    var charCode = e.key.charCodeAt(0);
    if (!((charCode >= 0x30 && charCode <= 0x39) || (charCode >= 0x41 && charCode <= 0x7a))) {
        e.preventDefault();
    }
});

jQuery('#test').on('keyup', function(e) {
    jQuery(this).val(jQuery(this).val().toUpperCase());
});
input#test {
    text-transform: uppercase;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test">

If you use the second condition with the upper 'Z' (0x5a), then the keyup conversion to upper event call is pointless, because you won't have any lower charcters input.

Upvotes: 0

Christian Vincenzo Traina
Christian Vincenzo Traina

Reputation: 10414

You can use a regular expression to replace each special character to void.

jQuery(document).ready(function() {
    jQuery('.uppercase').keyup(function()
    {
        jQuery(this).val(jQuery(this).val().replace(/[^\w\s]/gi, '').toUpperCase());
    });
});

You are sending what specified by regular explession to void character ('').

In the regular expression you can see the key ^ which means not, the key \w which means alphanumeric characters and \s which means spaces characters. So you are sending to void everything that's not alphanumeric and that's not space.

Remove \s inside the RegEx if you dont't want to allow spaces in your field.

PS. this does not prevent a user to submit special characters, you have to check server-side.

An equivalent -but cleaner- regular expression could be:

/\W/gi

You can check the link above to see what this does mean

Upvotes: 0

Related Questions