用于e.key的Javascript正则表达式回退(Safari)

时间:2016-09-19 14:54:55

标签: javascript regex validation safari

我有几个自定义元素,我需要运行正则表达式来验证它们。我正在使用按键事件。我有一个字母数字输入,我需要阻止所有特殊字符,除了: 数字 正常的字母 括号,斜线,破折号

这是我正在使用的函数,它在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();
    }
}

这是我正在使用的正则表达式,它工作正常:

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

但是,我发现Safari不支持event.key所以我不得不创建一个小后备来捕获它。现在,我将返回event.keyCode(返回已按下的键的整数),而不是event.key(返回实际的字符串)。但是,如果我想逃避*角色,我怎么逃避*同时让实际数字8仍然通过?

不确定解决此问题的最佳方法。非常感谢投入。

2 个答案:

答案 0 :(得分:4)

您可以使用String.fromCharCode转换回字符串文字:

var myKey = String.fromCharCode(evt.keyCode)

通过这种方式,您可以重用以前的regexp匹配器,而不是实现单独的逻辑。

答案 1 :(得分:1)

有一些关于您的代码段的内容应该引起您的注意。这是适度重构的版本:

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. 三元未正确构建(并且没有必要)。只需使用布尔表达式的结果作为handled的值。这是开发人员在使用三元表达式时常见的陷阱。

  2. 请勿将varconst混在一起。你可以,但你不应该。

  3. typeof <VAR> !== 'undefined'优于<VAR> !== undefined。您的条件不会抛出错误,因为Javascript中对对象文字(例如object.a)的属性访问不会抛出未定义的标识符引用抛出的方式。但是,最好与条件中的undefined检查一致,typeof <VAR> !== 'undefined'更安全。

  4. 至于您的具体问题,请查看String.fromCharCode(..)以重新使用您已编写的逻辑。