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 +
this is very nice and good
This is amazing…
Gr8 job!!!!
[...] method as it throws up the most searches. You can find about these here, here, here, and here (and many [...]
it is very good.
This is fantastic……….
Keep up the good work
good one..gullii..
Hey Dude,
Its gr8 solution, keep it up
just beyond the imagination …i liked it……gr8 job
Good
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”
}
Tahnks
gr8 job
so faar i used parseInt() and isNaN()..i think wat u r doing is mmore good..thak u very much dude
How about this one???
function isNumeric(str){
var numRegex = !/^-?\d+$/;
return numRegex.test(str.value);
}
This number validation is very useful to me to implement large projects
It is a very good validation. Very simple.
Thank you!
good
you’re GREAT!!!!!!! awesome!
Thank you very much
Nice tips.
Thanks
Hi,
Really nice work…
Thanks very much
Rams
wow … i have tried multiple solutions and candidly didn’t think this would work… very elegant very nice … and thanks vrry much
Thanks Friend. It helped me.