I am using Javascript to restrict the characters of various text entry fields as a form of client-side validation as well as improved usability. I am using the following code to do this:
function validNumbers(caller) {
var exp = /^[\d.]+/g;
var str = '';
if (caller.value.match(exp)) {
str = caller.value.match(exp).toString();
} else {
str = '';
}
str = str.replace(/\D/g,'');
caller.value = str;
}
I call this function with onkeypress="validNumbers(this);" and, for the most part, it works like a charm. The problem is that, when I type an invalid character into the field, the value of the field seems to get updated (from the point of view of the Javascript) but the character remains until I hit the next key, at which point it is replaced by the value of the next key visually, even if the next key is invalid as well. The desired effect is that, when an invalid key is pressed, the invalid value doesn't even show up visually. How do I accomplish this?
Edit: I selected the answer below because it got me on the right track. I did have to make sure to add e.shiftKey to my list of excluded events in order to prevent characters like "!@#$%^&*()_+", but that wasn't an issue for me to find out on my own.