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?