negative number validation using javascript

When you need to restrict user to enter negative numbers in input field,
You can achieve using jQuery as explained below.

Add jQuery latest file into your header.

<input type="text" name="test" id="test">

$("#test").keyup(function() {
    var val = $("#test").val();
    if (parseInt(val) < 0 || isNaN(val)) {
        alert("please enter valid values");

Check out working code in action
It will also not allow user to enter alphabet letters like A to Z.

Please leave your suggestions & comments if you found above code useful, so when other person read this blog, he/she can use above code with confidence.


8 thoughts on “negative number validation using javascript

  1. Its not working for negative numbers.
    For that we have to put ‘OR’ condition instead of ‘AND’ condition as follows :

    value = document.getElementById(‘ID’).value;

    if (parseInt(value) < 0 && isNaN(value))
    alert("please enter valid values");
    document.getElementById('iD').value = ' ';


    • Hello subha,

      Thanks for your feedback.
      We cant put if (parseInt(value) < 0 && isNaN(value)) because if one of 2 condition will not satisfy , then it will not validate.


I like to hear from you about this !!

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.