JavaScript Number Validation (Integer)

***If this post helped you, please support this blog by clicking one of the links on this page. Thanks :) ***

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 +

22 Responses to “JavaScript Number Validation (Integer)”

  1. srinivas.m Says:

    this is very nice and good

  2. Garima Says:

    This is amazing…

    Gr8 job!!!!

  3. Integer validation in Javascript - How to check if a number is an Integer - Noticias externas Says:

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

  4. p.LaghupathiReddy Says:

    it is very good.

  5. Ananyo Banerjee Says:

    This is fantastic……….

    Keep up the good work :)

  6. Tridib Says:

    good one..gullii..

  7. santosh Says:

    Hey Dude,

    Its gr8 solution, keep it up

  8. aditi Says:

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

  9. Pillai Says:

    Good

  10. Tilly Bean Says:

    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. ra Says:

    Tahnks

  12. harilal Says:

    gr8 job

  13. harilal Says:

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

  14. Kumar Chetan Sharma Says:

    How about this one???

    function isNumeric(str){
    var numRegex = !/^-?\d+$/;
    return numRegex.test(str.value);
    }

  15. Sakthivel Says:

    This number validation is very useful to me to implement large projects

  16. saikrishna Says:

    It is a very good validation. Very simple.
    Thank you!

  17. ramya Says:

    good

  18. ahmad Says:

    you’re GREAT!!!!!!! awesome!
    Thank you very much :D

  19. Pinna Infotech Says:

    Nice tips.

    Thanks

  20. Rams Says:

    Hi,

    Really nice work…

    Thanks very much

    Rams

  21. mark n tejas Says:

    wow … i have tried multiple solutions and candidly didn’t think this would work… very elegant very nice … and thanks vrry much

  22. Krishnan Says:

    Thanks Friend. It helped me.

Leave a Reply