JavaScript Number Validation (Integer)
To validate an integer in JavaScript, use a regular expression:
var NumberToTest = 15;
var IsFound = /^-?\d+$/.test(NumberToTest);
document.write(IsFound);
The ^ symbol specifies that the tested value must begin with a digit (i.e., there can be no non-numeric data before the numeric data begins). The $ symbol is similarly used to ensure that no non-numeric data comes after the numeric data.
The + symbol matches one or more occurrences of the previous item. In this case, it means that there can be one or more digits in the test string. Without this, 15 would not validate because the test would be looking for a string that started and ended with one digit.
Related Articles:
JavaScript Regular Expressions
JavaScript Regular Expression Special Characters: $ ^
JavaScript Regular Expression Plus Sign +
May 21, 2007 at 6:45 am
this is very nice and good
June 14, 2007 at 6:19 am
This is amazing…
Gr8 job!!!!
August 10, 2007 at 11:20 am
[...] method as it throws up the most searches. You can find about these here, here, here, and here (and many [...]
August 24, 2007 at 10:09 am
it is very good.
September 3, 2007 at 12:55 pm
This is fantastic……….
Keep up the good work
December 10, 2007 at 10:59 pm
good one..gullii..
December 27, 2007 at 1:21 am
Hey Dude,
Its gr8 solution, keep it up
February 26, 2008 at 4:01 am
just beyond the imagination …i liked it……gr8 job
March 11, 2008 at 12:19 pm
Good
June 24, 2008 at 6:20 am
Finally an integer test that works, thank you!
Working example:
if (!/^-?\d+$/.test(fld.value))
{
fld.style.background = ‘Red’;
error = “Please use numbers only.\n”
}
September 12, 2008 at 4:46 pm
Tahnks
October 6, 2008 at 2:11 am
gr8 job
October 6, 2008 at 2:13 am
so faar i used parseInt() and isNaN()..i think wat u r doing is mmore good..thak u very much dude
November 14, 2008 at 5:29 am
How about this one???
function isNumeric(str){
var numRegex = !/^-?\d+$/;
return numRegex.test(str.value);
}
December 9, 2008 at 11:41 pm
This number validation is very useful to me to implement large projects
January 27, 2009 at 10:12 pm
It is a very good validation. Very simple.
Thank you!
February 19, 2009 at 11:59 pm
good
February 24, 2009 at 3:34 pm
you’re GREAT!!!!!!! awesome!
Thank you very much
April 26, 2009 at 1:40 am
Nice tips.
Thanks
November 21, 2009 at 7:54 am
Hi,
Really nice work…
Thanks very much
Rams
January 26, 2010 at 2:46 pm
wow … i have tried multiple solutions and candidly didn’t think this would work… very elegant very nice … and thanks vrry much