Home > database >  How to prevent special characters using event.keycode in javascript
How to prevent special characters using event.keycode in javascript

Time:11-02

Hi I want to know what is the exact event.keycode number values for below special characters ! @ # $ % ^ & * ( ) .

I have the below code.

$(window).keydown(function (event) {
    if (event.keyCode == 116 || event.keyCode == 93 || event.keyCode == 33 ||
        event.keyCode == 34 || event.keyCode == 123 || event.keyCode == 154 ||
        event.keyCode == 82 || event.keyCode == 17 || event.keyCode === 38 ||
        event.keyCode === 40 || event.keyCode === 13 
     ) {
        event.preventDefault();
        return false;
    }
    
    
});

I want to use the above function and prevent the special characters from typing when using mobile devices.

I tried the below event.keycode numbers . But the same is not working.

        event.keyCode == 161 || event.keyCode == 64 || event.keyCode == 163 ||
        event.keyCode == 164 || event.keyCode == 165 || event.keyCode == 160 ||
        event.keyCode == 166 || event.keyCode == 171 || event.keyCode === 168 ||
        event.keyCode === 169

I am trying to find the solution and learn in the process.

CodePudding user response:

Using the .key property (Documentation) which will return the pressed key's character, and an array includes, we can significantly simplify this:

const forbiddenChars = ['@', '#', '$', '%', '^', '&', '*', '(', ')', '.']

$(window).keydown(function(event) {
  if (forbiddenChars.includes(event.key)) {
    console.log('Key prevented')
    event.preventDefault();
    return false;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea></textarea>

CodePudding user response:

Simplest would probably be with RegExp.

$(window).keydown(function (event) {
  var regex = new RegExp("^[a-zA-Z0-9] $");
  if (!regex.test(event.key)) {
    event.preventDefault();
    return false;
  }
});
  • Related