开发者

Problems with dynamic RegExp construction in Javascript

This method is to prevent users from entering anything but numbers and "allowed characters." Allowed characters are passed as the parameter allowedchars.

So far, the method prevents number entries but the allowedchars doesn't work (tried with passing "-" (hyphen) and "." (period)). So I'm assuming my dynamic regex construction isn't correct. Help?

Thanks in advance!

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.preventDefa开发者_StackOverflowult) {
                theEvent.preventDefault();
            }
        }
}

(ps. jQuery solutions are fine too)


1. When you construct via new RegExp, there's no need to include the surrounding /s.

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

2. But if addToRegex contains ] or -, the resulting regex may become invalid or match too much. So you need to escape them:

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

3. But since you are checking against 1 character anyway, it may be easier to avoid regex.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜