views:

89

answers:

2

I have an input text field that needs to be limited as to what characters can be typed in. As one form of defense against faulty input, I'm trying to not even let the user type in incorrect things. The input can be [a-zA-Z-._] characters and is limited to 32 characters.

<input id="aliasEntry" type="text" maxlength="32">

As you can see, I've already got the 32 character limit figured out, and the user is prevented from typing any more after the limit has been reached. But I'm having a problem with preventing the input of incorrect characters.

I've tried using jquery's .keypress() and .keydown() event catchers to do things similar to the following:

$("#aliasEntry").keypress(function(e)
{
    var code = e.which || e.keyCode;
    // 65 - 90 for A-Z and 97 - 122 for a-z 95 for _ 45 for - 46 for .
    if (!((code >= 65 && code <= 90) || (code >= 97 && code <= 122) || code == 95 || code == 46 || code == 45))
    {
        var text = $("#aliasEntry").val();
        text = text.substring(0,text.length);
        $("#aliasEntry").val(text);
    }
});

But The problem with this is that the browsers always insert the typed character into the text box AFTER the event has been handled, which makes the code useless because the character I'm trying to eliminate hasn't been entered yet. Is there a way to simply prevent the browser from inserting the character into the text box after the user types it?

+2  A: 

You're using jQuery, so see this:http://api.jquery.com/event.preventDefault/. Just call e.preventDefault() if the character happens to be invalid, and this should prevent the default browser action from occurring, which in this case would be the insertion of a character.

l33tnerd
And do it during `keypress`; in Opera, you can't prevent the default action during `keydown`.
Marcel Korpel
Yep works great. I was looking in that direction as well to figure out if the event could simply be stopped, but I was messing with the wrong methods. Thanks!
JDC
+1  A: 

Remember to do server-side validation as well. Client validation is really easy to fool (turn off JavaScript on my browser in this case)

Nate Zaugg
So true, but this should be a comment, not an answer. Please bear in mind next time.
Marcel Korpel