0

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;
};
2
  • 1
    Exact duplicate: HTML Text Input allow only Numeric input Commented Aug 3, 2012 at 8:26
  • i took code from that question, but did some changes, and now it doesnt works as intend Commented Aug 3, 2012 at 8:27

1 Answer 1

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

1 Comment

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

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.