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 +

5 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 :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.