'Is there a way to stop the user from typing in a textbox after they enter a bad character?

I don't want to disable the input box, I'd like to either delete the bad character or allow the user to delete it.

So far I've tried to set the max length of the input to the length where the bad character was entered, but I was still able to type after that.

Here is a sample of the function I'm working on:

function validateCharacterName() {
var value = document.getElementById("characterName").value;
var message = document.getElementById("characterNameMessage");
var button = document.getElementById("confirmButton")

if (value.length <= 1) {
    message.innerText = "Name must be two or more characters."
    disableButton(button)
} else {
    for (var counter = 0 ; counter < value.length; counter++) {
        var character = value.charAt(counter);

        if (isAlpha(character) && !isDigit(character)) {
            message.innerText = "";
            enableButton(button);
        } else {
            message.innerText = "Character '" + character + "' is invalid.";
            disableButton(button);
        }
     }
}

}



Solution 1:[1]

The recommended way to ensure the entered text only contains expected characters is using the the pattern attribute. This works slightly different than you suggest, but will be more in line of what the user would expect, as it is a very common way how to do this. Here you can see this in action.

To be specific here is an example how you avoid the letter "a":

<input type="text" pattern="[^a]*" title="Please avoid the letter 'a'">

The pattern attribute uses regular expressions. This does need some getting used to, but is rather powerful. In this case the ^ insider the [] means "not". The a means "a" and the * means allow any number of appearances of the previous thing. In summary this means allow any number of any character not being an "a".

You might want to use a whitelist approach rather than a blacklist approach. For example to allow any Latin letters you could use:

<input type="text" pattern="[a-zA-Z]*" title="Please use letters only">

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1