1

I have this code, but somewhy when i use this function to validate my input field everything works, except + and - keys, even thought i noted them as true. What have i done wrong?

function validateNumber(event)
{
    var key = window.event ? event.keyCode : event.which;

    if (event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 37 ||
        event.keyCode == 39 || event.keyCode == 107 || event.keyCode == 109 ||
        event.keyCode == 32 )
    {
        return true;
    }
    else if(key < 48 || key > 57)
    {
        return false;
    }
    else return true;
};
Hubro
  • 56,214
  • 69
  • 228
  • 381
Avdept
  • 2,261
  • 2
  • 26
  • 48
  • 1
    Exact duplicate: [HTML Text Input allow only Numeric input](http://stackoverflow.com/questions/469357/html-text-input-allow-only-numeric-input) – Andreas Aug 03 '12 at 08:26
  • i took code from that question, but did some changes, and now it doesnt works as intend – Avdept Aug 03 '12 at 08:27

1 Answers1

2

I don't see you checking for 189 (-) and 187 (=, which is really what happens when you type +). You might want to check if the Shift key is pressed for +.

As already noted, it's overall a wrong way to validate user input. You need to inspect the value of the input, not individual keystrokes.

First, define a validation function that would check an arbitrary text with a regexp:

function checkArithmetic(str) {
    var regexp = /^[0-9+-]$/;
    return regexp.test(str);
}

Next, add a handler to your input element:

input.addEventListener('input', function (e) {
    var value = input.value;

    if (checkArithmetic(value)) {
        // OK!
    } else {
        // error
    }
}, false);
katspaugh
  • 17,449
  • 11
  • 66
  • 103
  • the problem is that i dont have access to form by itself, i can only use some js, to do any actions based on id – Avdept Aug 03 '12 at 08:33