Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
1.80/5 (2 votes)
See more:
I would like to validate the numeric input with negative number, how can I do that?




Thanks
Posted
Comments
PIEBALDconsult 3-Jun-15 0:09am    
By not pressing any other keys.

First of all, please see this simple tutorial on more detail on input control filtering with JavaScript with better code: http://www.javascripter.net/faq/keyboardinputfiltering.htm[^].

Also, these are the very useful resources used to find out what to filter:
http://www.asquare.net/javascript/tests/KeyCode.html[^],
http://unixpapa.com/js/testkey.html[^].

Solution 1 gives you the right idea, but, unfortunately, does not solves the problem. It does filter out all except minus sign, decimal digits and backspace (important thing: 8). But on top of it, you need some validation anyway. This is because minus sign can be misplaced or added twice, or the number of digits can be too big, in other words, the input still can be invalid. Besides, you may need to additionally check up the data for some required range.

Therefore, you cannot get away without the validation. The best initial step of validation would be to actually parse the string into number. In addition to the validation, you will get the number itself, which you should use. Please see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt[^].

Only now you got everything to deal with numeric input in your case.

—SA
 
Share this answer
 
v2
Comments
Member 11707186 3-Jun-15 0:49am    
Thanks Sergey for detailing the fact!
Sergey Alexandrovich Kryukov 3-Jun-15 0:54am    
You are very welcome.
Good luck, call again.
—SA
You can use the script as below:
XML
<div>
    <input id="txtNum" type="text" onkeydown="functionAllNum();" />
</div>

<script>
    function functionAllNum() {
        var num = document.getElementById("txtNum").value;
        if (num == "") {
            if ((event.keyCode < 48 || event.keyCode > 57) && event.keyCode != 189) {
                event.preventDefault();
                alert("Please Enter Number Only");
            }
        } else {
            if ((event.keyCode < 48 || event.keyCode > 57) && event.keyCode != 8) {
                event.preventDefault();
                alert("Please Enter Number Only");
            }
        }
    }
</script>
 
Share this answer
 
Comments
Member 11707186 2-Jun-15 22:57pm    
Thanks for your quick response
Sergey Alexandrovich Kryukov 3-Jun-15 0:46am    
Not quite. This doesn't solve the problem yet. Please see Solution 2 where I explain it and advise what else should be done.
Thank you for your understanding.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900