代码之家  ›  专栏  ›  技术社区  ›  Kyle Cureau

Javascript中动态RegExp构造的问题

  •  1
  • Kyle Cureau  · 技术社区  · 14 年前

    此方法防止用户输入除数字和“允许的字符”以外的任何内容。允许的字符作为参数传递 allowedchars

    到目前为止,该方法阻止数字条目,但allowedchars不起作用(尝试传递“-”(连字符)和“.”(句点))。所以我假设我的动态正则表达式构造不正确。救命啊?

    numValidate : function (evt, allowedchars) {
        var theEvent, key, regex,
        addToRegex = allowedchars;
    
        theEvent = evt || window.event;
        key = theEvent.keyCode || theEvent.which;
            key = String.fromCharCode(key);
            var regex = new RegExp('/^[0-9' + addToRegex + ']$/');
            if (!regex.test(key)) {
                theEvent.returnValue = false;
                if (theEvent.preventDefault) {
                    theEvent.preventDefault();
                }
            }
    }
    

    (另外,jQuery解决方案也不错)

    1 回复  |  直到 14 年前
        1
  •  2
  •   kennytm    14 年前

    1 当你通过 new RegExp ,不需要包括周围环境 /

        var regex = new RegExp('^[0-9' + addToRegex + ']$');
    

    2 但如果 addToRegex 包含 ] - ,生成的正则表达式可能会变得无效或匹配过多。所以你需要逃离他们:

        var regex = new RegExp('^[0-9' + addToRegex.replace(/([\-\]])/g, '\\$1') + ']$');
    

    三。 但是,由于您是针对1个字符进行检查,因此 正则表达式。

        var pass = ("0123456789" + addToRegex).indexOf(key);
        if (pass == -1) {
          ...