Question

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.

Was it helpful?

Solution

In your function you are clearing the value after it has been entered into the textfield and evaluated. Instead, you need to prevent it from being entered into the textfield altogether. To accomplish this, you want to use the keydown's preventDefault() method:

onkeydown="function(e) { validNumbers(e); }"

function validNumbers(e) {
    if (e.keyCode == 1 || e.keyCode == 2 ... etc) {
        e.preventDefault();
    }
}

This will block specific characters (reference here) from ever entering the input field. Note that this will not block copy and paste so you will either still need to evaluate the entire string 'onpaste' or prevent 'onpaste' with a similar event handler.

This is also not a cross-brower solution but should get your feet plenty wet. See this JSFiddle for a live example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top