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
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
Share Improve this question edited May 24, 2010 at 16:04 Doug Neiner 66.2k13 gold badges110 silver badges118 bronze badges asked May 24, 2010 at 16:03 Mo.Mo. 42.5k37 gold badges90 silver badges133 bronze badges 3- Are real numbers allowed ? Or just integers. – nc3b Commented May 24, 2010 at 16:05
- 1 stackoverflow.com/questions/18082/… – Robert Harvey Commented May 24, 2010 at 16:05
- try to take the square root, trap for errors. – Stephanie Page Commented May 24, 2010 at 17:41
10 Answers
Reset to default 7If 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
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.
I use jquery and a AlphaNumeric plugin, see here for a demo
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
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;
}
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.
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.
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.
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>