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 Answer 1

2

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) {
      ...
Sign up to request clarification or add additional context in comments.

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.