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 +

13 Responses

  1. this is very nice and good

  2. This is amazing…

    Gr8 job!!!!

  3. [...] method as it throws up the most searches.  You can find about these here, here, here, and here (and many [...]

  4. it is very good.

  5. This is fantastic……….

    Keep up the good work :)

  6. good one..gullii..

  7. Hey Dude,

    Its gr8 solution, keep it up

  8. just beyond the imagination …i liked it……gr8 job

  9. Good

  10. 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”
    }

  11. gr8 job

  12. so faar i used parseInt() and isNaN()..i think wat u r doing is mmore good..thak u very much dude

Leave a Reply