Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I validate that value entered into an input box is just numbers?

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

like image 920
Mo. Avatar asked May 24 '10 16:05

Mo.


2 Answers

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
}
like image 156
nc3b Avatar answered Sep 18 '22 11:09

nc3b


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

like image 39
skyfoot Avatar answered Sep 20 '22 11:09

skyfoot