0

I'm trying to prevent non-numeric characters being entered in a text field. My code validates the characters but doesn't stop it being added to text box.

My code:

var isNumberKey = function(e){
    //alert(e.which);
    if (e.which > 31 && (e.which < 48 || e.which > 57)) 
        return false;   
    return true;
}

var isBackSpaceKey = function(e){
    return e.which == 8;
}

var isArrowKey = function(e) {
    return e.which >= 37 && e.which <= 40;
}

var inputs = $$('.numberOnly');
inputs.addEvent('keyup', function(e){
    console.log(e.which);
    if (!isNumberKey(e) && !isBackSpaceKey(e) && !isArrowKey(e)){
        e.stop();
        return false;
    }
    return true;
});

HTML:

<input name="t1" type="text" class="numberOnly" id="t1"/>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
KoolKabin
  • 17,157
  • 35
  • 107
  • 145

1 Answers1

1

you should use the keydown event instead of the keyup. I'd do it like this:

var inputs = $$('.numberOnly');
inputs.addEvent('keydown', function(e){
    if (e.code >= 48 && e.code <= 57 ){
        return true;
    }
    e.stop();
    return false;
});

http://jsfiddle.net/TsAkb/

Hope this helps

EDIT:

Maybe you'd want to allow the "tab" key ,the "enter" key and the "backspace" too =P

pleasedontbelong
  • 19,542
  • 12
  • 53
  • 77
  • 1
    +1 for keydown, as for testing, this looks kind of reasonable to me: `(e.key && e.key.test(/([\d]|tab|backspace|enter|left|right|up|down)/)) || e.stop();` – Dimitar Christoff May 24 '12 at 13:22
  • in fact: `(e.key && e.key.test && e.key.test(/([\d]|tab|backspace|delete|enter|left|right|up|down)/)) || e.stop();` - needs an extra check as some num pad keypresses are not normalized to strings by mootools and calling `.test` would be unsafe. can also be `e.key && e.key.length && ... ` or it can get duct typed to string just to be safe. – Dimitar Christoff May 24 '12 at 13:30
  • http://jsfiddle.net/dimitar/TsAkb/2/ -> need to add a check for shift status also and convert e.key to string if it comes as number (num pad does). – Dimitar Christoff May 24 '12 at 13:37
  • Super! I didn't knew you could have a "paste" event :P – pleasedontbelong May 24 '12 at 14:19