views:

20

answers:

1

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

(ps. jQuery solutions are fine too)

+1  A: 

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) {
      ...
KennyTM
@Emile: #2 works fine for me.
KennyTM
Sorry @KennyTM...you are totally right. I thought I had copied and pasted it but chopped out a bracket from the middle, mid-ether. :) I've deleted my prior comment. Thanks for the answer!
Emile