streetlight
streetlight

Reputation: 5968

Regex for only characters 0-9?

I'm trying to find/utilize a regex for only the characters 0-9. If possible, I'm also trying to enable the user to utilize their normal keys (backspace, left and right arrows, backspace).

In addition, I want to stop . (periods), % (percentages), and ' (single quotes).

This is what I have so far, but it is not stopping the above three issues:

function onlyNumbers(evt) {
        var theEvent = evt || window.event;
        var key = theEvent.keyCode || theEvent.which;
        key = String.fromCharCode( key );
        var regex = /[0-9]/;
        //alert(theEvent.keyCode)
        if( !regex.test(key) && theEvent.keyCode!='8' && theEvent.keyCode!='46'&& theEvent.keyCode!='37' && theEvent.keyCode!='39') {//keyCode8 = backspace
            theEvent.returnValue = false;
            if(theEvent.preventDefault) theEvent.preventDefault();
        }
    }

Upvotes: 0

Views: 695

Answers (2)

Anirudha
Anirudha

Reputation: 32797

You should use || instead of &&

You can also use the regex[^.%'].it matches any character except .,%,'

Upvotes: 2

jbabey
jbabey

Reputation: 46647

I would use an array of allowed keyCodes and check against that:

function onlyNumbers(evt) {
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;

    // 0-9, backspace, left and right arrows
    var allowedKeyCodes = [48,49,50,51,52,53,54,55,56,57,8,37,39]; 

    if(allowedKeyCodes.indexOf(key) === -1) {
        theEvent.returnValue = false;
        if(theEvent.preventDefault) theEvent.preventDefault();
    }
}

Upvotes: 1

Related Questions