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;
};
I don’t see you checking for
189(-) and187(=, 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:
Next, add a handler to your input element: