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 +
Filed under: Internet, JavaScript, Programming, Software, Web
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