James James - 1 year ago 169
Javascript Question

Javascript Regular Expression Fallback for e.key (Safari)

I have a couple of custom elements that I need to run regular expressions on to validate them. I'm using the keypress event. I have an alpha-numeric input and I need to prevent all special characters except:
1. numbers
2. normal letters
3. parenthesis, slash, dash

Here's the function I'm using that gets called on keypress:

function keypress(e) {
// Ensure that it is alphanumeric and stop the keypress
var handled = false;
if (e.key !== undefined) {
const regx = /^[0-9a-zA-Z.-\s/&]+$/;
!regx.test(e.key) ? handled = true : handled = false;
} else if (e.keyCode !== undefined) {
const char = e.which || e.keyCode;
char === 106 || char === 107 ? handled = true : handled = false;

if (handled) {

Here's the regular expression that I'm using and it works fine:

const regx = /^[0-9a-zA-Z.-\s/&]+$/;

However, I found out that Safari doesn't support event.key so I had to create a little fallback for it to catch. Now, instead of event.key (which returns the actual character string), I'm returning event.keyCode (which returns an integer of the key that was pressed). But, if I want to escape the * character, how do I escape * while letting the actual number 8 still pass?

Not sure the best way to tackle this. Input is greatly appreciated.

Answer Source

You can use String.fromCharCode to convert back to string literals:

var myKey = String.fromCharCode(evt.keyCode)

With this, you can reuse your previous regexp matcher instead of implementing a separate logic.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download