6

I have a keydown event and I want it to be triggered when I press alphanumeric or special characters like #$@.

 <input type="text" style="width: 70%;" [(ngModel)]= "textMessage" (keydown) ="sendTypingEvent()" > 

I want to restrict the event NOT to be triggered at all for keys such as enter, escape (esc), shift, alt, tab, backspace and command (meta), arrows and f keys (f1 though f12).

Is there a way to set up a REGEX pattern at the HTML?

<input (keydown.a)="..."> --expect to trigger 

I can have the event triggered and filter the key at the function call as shown below. However, trying to see if there are any other options.

sendTypingEvent(event) { if (event.key === "Enter" || event.key ==='esc' .... ) { console.log("skip this event"); } } 

2 Answers 2

9

Here are two ways to restrict keydown event -

  1. you allow the alphanumeric key press only
sendTypingEvent(event){ if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 65 && event.keyCode <= 90)){ console.log("input was 0-9"); console.log("input was a-z"); return true; } return false; } 
  1. You can restrict specific keys
sendTypingEvent(event){ if ((event.keyCode >= 112 && event.keyCode <= 123) || event.keyCode == 16){ console.log("Disabled f11 to f12, shift keys"); return false } } 

Get Keycode for this website -

https://keycode.info/

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

2 Comments

He is asking for regex
Without regex and including all non-functional keys 😜 (event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 65 && event.keyCode <= 90) || (event.keyCode >= 96 && event.keyCode <= 111) || (event.keyCode >= 186 && event.keyCode <= 222)
3

document.getElementById("myinput").addEventListener("input", function(event) { if (/[!'^+%&/()=?_\-~`;#$½{[\]}\\|<>@,]/gi.test(event.data)) { console.log(event.data) // or // your operation } })
<input id="myinput" type="text" style="width: 70%;">

In your case, you should edit your trigger function as below, it will show only special characters on console

sendTypingEvent(event) { if (/[!'^+%&/()=?_\-~`;#$½{[\]}\\|<>@,]/gi.test(event.key)) { console.log(event.key); } } 

1 Comment

Thanks for the answer. Will check and mark it as answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.