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
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
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With