0

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) {
        e.preventDefault();
    }
}

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.

Brandon
  • 3,074
  • 3
  • 27
  • 44

2 Answers2

4

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.

mdziekon
  • 3,531
  • 3
  • 22
  • 32
1

There are a few things about your code snippet that should be called to your attention. Here is the moderately refactored version:

function keypress(e) {
    let handled = false;

    if (typeof e.key !== 'undefined') {
        const regx = /^[0-9a-zA-Z.-\s/&]+$/;

        handled = !regx.test(e.key);
    }
    else if (typeof e.keyCode !== 'undefined') {
        const char = e.which || e.keyCode;

        handled = (char === 106 || char === 107);
    }

    if (handled) {
        e.preventDefault();
    }
}
  1. Ternaries aren't properly constructed (and they aren't necessary). Just use the result of the boolean expression as the value for handled. This is a common trap developers fall into when using ternary expressions.

  2. Don't mix var with const. You can, but you shouldn't.

  3. typeof <VAR> !== 'undefined' is preferable to <VAR> !== undefined. Your conditionals don't throw an error because property access on object literals (e.g. object.a) in Javascript doesn't throw the way that an undefined identifier reference throws. It is preferable, however, to be consistent with undefined checks in conditionals, and the typeof <VAR> !== 'undefined' is safer.

As for your specific problem, take a look at String.fromCharCode(..) to re-use the logic you have already written.

wpcarro
  • 1,528
  • 10
  • 13