-1

I am trying to create a regex that only registers the alphabet on the standard English keyboard (a-z). However, the regex I currently have also registers the keys that start with letters... So ctrl, alt, shift, caps lock, etc. are recognized as valid keys pressed. I want to exclude these special keys however I can.

Here is what I have so far...

Register key down:

componentDidMount() {

      document.addEventListener("keydown", this.handleKeyDown);

};

Validate if key is alphabetic:

handleKeyDown = (event) => {
        const regex = /^[A-Za-z]+$/

        // validate key press is alphabetic
        if( regex.test(event.key) ) {
        
            console.log(event.key);

         } else {

            console.log(event.key);

        };
            
    };
Justin
  • 61
  • 6
  • 1
    You have a regex that allows any amount of characters in the string. Since all valid "key" values are a single character for your purposes, change your regex to allow only one character ie remove the plus sign from the regex pattern. – James Oct 20 '20 at 15:53
  • Do you just want to match a single letter string? `const regex = /^[A-Za-z]$/`? – Wiktor Stribiżew Oct 20 '20 at 15:57
  • Both `if` and `else` return `console.log(event.key)`. How are you even checking (in code) that the regex works or not? – HoldOffHunger Oct 20 '20 at 16:33
  • James's and Wiktor's solution appears to have worked. Thank you for that! HoldOffHunger, that was just a snippet of the project to show what key is being pressed. It was only being used to show what key was being pressed. Its just an example. – Justin Oct 20 '20 at 17:25

2 Answers2

0

your regex is fine but remove the + sign if you want only 1 character.

Running Example: https://jsfiddle.net/uxa0zkor/

var msg = document.getElementById('state-msg');
document.body.addEventListener('keydown', function(e) {
    const regex = /^[A-Za-z]$/

        // validate key press is alphabetic
        if( regex.test(e.key) ) {
        
            //console.log(event.key);
            msg.textContent = "a-z or A-z  " + e.keyCode;

         } else {

            //console.log(event.key);
            msg.textContent = "other than a-z or A-z " + e.keyCode;

        };
});
Kamran Pervaiz
  • 1,702
  • 3
  • 17
  • 39
0

You don’t need regex for that. Just check against ‘keyCode’ if it’s between the acceptable range.

Uppercase letters are between 65 (A) and 90 (Z). Lowercase are between 97 and 122.

siaznik
  • 496
  • 2
  • 5