6

I was wondering what the best and easiest way was to ensure that the value a user enters into an input box is numeric in a web page? either notify them they are not allowed to when they edit it or not allow them to enter in non numeric values to begin with.

any ideas?

thanks

Doug Neiner
  • 65,509
  • 13
  • 109
  • 118
Mo.
  • 40,243
  • 37
  • 86
  • 131

10 Answers10

7

If only integer values are allowed, I would try something like:

if( isNaN(parseInt(str, 10)) ) {
    //error
}

EDIT: @M28 and @unomi are right, this might allow some inputs that aren't really numbers. M28 posted a really good solution in the comments:

if( ! (parseInt(str, 10).toString() == str) ) {
    //error
}
Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
nc3b
  • 15,562
  • 5
  • 51
  • 63
3

You can use a regular expression ^\d*$

var re = new RegExp("^\d*$");
  if ($("#someinput").val().match(re)) {
    alert("Only numbers");
  } else {
    alert("No match");
  }

^ tells the expression to start matching from the beginning of the string. 
\d is a match for numbers which is the same as [0-9] (any number from 0 to 9)
* tells to match all numbers in string.
$ tells the expression to match until the end of the string.

The $("#someinput").val() is jquery but you could use normal javascript as in: document.somepintput.value.match(re).

regular expressions are well worth learning as they can solve many problems in a neat and concise manner. Regular expressions

skyfoot
  • 20,629
  • 8
  • 49
  • 71
3

While nc3b is close, using parseInt will actually allow cases you might not want it to.

parseInt("133t",10)

results in: 133

Better to do

if(isNaN(Number(str, 10)){
  Error;
}

If you want to make sure that the whole string must be representative of a number.

unomi
  • 2,642
  • 18
  • 19
2

I use jquery and a AlphaNumeric plugin, see here for a demo

Rippo
  • 22,117
  • 14
  • 78
  • 117
  • Hi i have and i put in: at the bottom but it gives me a $(".datapoints").numeric is not a function error. thanks – Mo. May 24 '10 at 16:54
  • im sorry i dont know how to highlight the code in my comment, really sorry. – Mo. May 24 '10 at 16:55
  • Not sure without reviewing your code, maybe try and give your input an id='myid' and use $('myid').numeric(), also make sure you reference BOTH jquery and the the alphanumeric plugin. – Rippo May 24 '10 at 18:40
  • I suspect you are not adding a reference to jquery – Rippo May 24 '10 at 18:47
0

Already some good answers have been posted from nc3b and skyfoot.

But nc3b's answer may fail with input wich has leading zeros like 007 and allow exponential inputs.

And skyfoot's answer might not allow negative values and might allow empty strings.

In order to avoid those traps i have used below code snippet.

 $(document).ready(function(){
      $("input").change(function(){
      var enteredValue = $(this).val();
      var re = new RegExp("^[-+]?[0-9]+$");
      if (enteredValue != "" && re.test(enteredValue)) {
        alert("You have entered valid integer");
      } else {
        alert("This is not valid integer");
      }
        //alert("The text has been changed.");
      });
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("input").change(function(){

var enteredValue = $(this).val();
var re = new RegExp("^[-+]?[0-9]+$");
  if (enteredValue != "" && re.test(enteredValue)) {
    alert("You have entered valid integer");
  } else {
    alert("This is not valid integer");
  }
    //alert("The text has been changed.");
  });
});
</script>
</head>
<body>

<input type="text">
<p>Write something in the input field, and then press enter or click outside the field.</p>

</body>
</html>
Community
  • 1
  • 1
ManirajSS
  • 2,295
  • 5
  • 26
  • 50
0

you can have a javascript to check on a event that may use isNAN function to see the values entered are numbers or not.

if(isNaN($('input[type=text]').val())

bye the way isNaN means Not a Number

sushil bharwani
  • 29,685
  • 30
  • 94
  • 128
  • `$('input[type=text]').val()` will always return a string, even if only integers are entered, so this will always return `false`. – Matt May 24 '10 at 16:31
0

Your best bet by far is to leverage the work of someone who's already done this for you, via a validation library and/or input masking library. Don't reinvent the wheel, several nice round ones, with rims to suit just about any car, have already been invented for you.

Not linking a specific one here because that's not really the point, a search on "javascript form validation library" will find quite a few.

Edit I hadn't looked for a while, I have to say I like the look of this one. Both validation and masking, and not library-specific (though there's a jQuery plug-in available if you like). Again, linking them isn't really the point, but it looked cool enough to shout out.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

The code grabs the input value, and then checks from beginning to end and the {5} is number of digits (this is optional).

function validzip(){ txt1 = document.FormName.InputName.value; if (/^\d{5}$/ .test(txt1) == false){ /* Simpler/longer alternative to this is: if ((/[0-9]/g .test(txt1) == false) || (txt1.length != 5)){ */ alert('Not Valid'); return false; }

        return true;
    }

Tumharyyaaden
  • 2,733
  • 3
  • 19
  • 20
0

Use this with jQuery - http://digitalbush.com/projects/masked-input-plugin/

It will only allow numbers to be entered. It is also very easy to use and completely customise, not to mention light-weight.

Tim
  • 6,986
  • 8
  • 38
  • 57
0

On the client side, start with <input type="number"> (this will be treated as type="text" on browsers which don't yet support HTML5. Then use javascript (as suggested by others) for the non-HTML5 browsers.

Don't forget server-side validation too, in case people have javascript turned off.

TRiG
  • 10,148
  • 7
  • 57
  • 107