Wednesday, July 1, 2009

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.

Source : http://blog.techsaints.com/2007/04/10/javascript-number-validation-integer/

No comments:

Post a Comment