0

The desired effect is such that when the user types in any character that is not a letter or a number, that character is immediately removed; thus causing the text cursor to not advance.

After already trying to look for solutions online myself, here is what I have so far:

<input type="text" id="job-name" maxlength="20" pattern="[a-zA-Z0-9]+" style="width:200px; text-align:center;">

document.getElementById('job-name').addEventListener('keydown', function () {
            if (!document.getElementById('job-name').validity.valid) {
                var text = document.getElementById('job-name').value;
                text = text.slice(0,-1);
                document.getElementById('job-name').value = text;
            }
        });

The problem is that the check of the 'valid' attribute is thus far always true and never false, regardless of the character typed in, for some reason. My expectation was that whenever the character that was just typed in does not conform to the pattern, the 'valid' should return false; otherwise, it is true.

2 Answers 2

1

Use the event input to accomplish that:

This approach uses the regex /[^a-z0-9]+/i.

Basically, for every input char/text, the handle will replace with empty the invalid char.

document.getElementById('job-name').addEventListener('input', function(e) {
  this.value = this.value.replace(/[^a-z0-9]+/i, '');
})
<input type="text" placeholder='Paste text, drag text or type text' id="job-name" maxlength="20" style="width:400px; text-align:center;">

Sign up to request clarification or add additional context in comments.

Comments

0

Try using the input event instead of keydown.

document.getElementById('job-name').addEventListener('input', function () {
    if (!document.getElementById('job-name').validity.valid) {
        var text = document.getElementById('job-name').value;
        text = text.slice(0,-1);
        document.getElementById('job-name').value = text;
    }
});

1 Comment

That worked; albeit strange to me why that worked. Why would using 'input' suddenly cause the mere act of checking the 'valid' attribute to suddenly not always return true?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.