Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
41
rated 0 times [  48] [ 7]  / answers: 1 / hits: 18997  / 14 Years ago, mon, august 23, 2010, 12:00:00

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?


More From » html

 Answers
36

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.


[#95836] Friday, August 20, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sabinal

Total Points: 144
Total Questions: 112
Total Answers: 107

Location: Ghana
Member since Mon, Aug 22, 2022
2 Years ago
;