2.2 Testing a Number's Validity

NN 3, IE 4

2.2.1 Problem

You want to be sure a value is a number before performing a math operation on it.

2.2.2 Solution

If the value you're testing can come from any kind of source, the safest bet is to use the typeof operator on the value. Applying this operator to any numeric value evaluates to the string number. Therefore, using it in a conditional expression looks like this:

if (typeof someVal =  = "number") {
    // OK, operate on the value numerically

But some JavaScript methods, such as parseInt( ) and parseFloat( ), return a special value, NaN ("not a number"), signifying that they were unable to derive the number you desired. Operations expecting numeric operands or arguments that encounter values evaluating to NaN also generally return NaN. To test for this condition, use the isNaN( ) method, which returns true if the value is not a number. For example:

var myVal = parseInt(document.myForm.myAge.value);
if (isNaN(myVal)) {
    alert("Please check the Age text box entry.");
} else {
    // OK, operate on the value numerically

2.2.3 Discussion

Don't get the wrong impression about the isNaN( ) method from the second example just shown. It is not a suitable approach to validating numeric input to a text box. That's because the parseInt( ) or parseFloat( ) methods return the first numbers (if any) they encounter in the string value passed as an argument. If someone enters 32G into a text box intended for an age, the parseInt( ) method pulls off the 32 portion, but the full value of the text box is not valid for your database that expects a strictly numeric value for that field. See Recipe 8.2 for more robust ways of validating numeric text entries.

You don't have to perform validity testing on absolutely every value about to undergo a math operation. Most values in your scripts tend to be under strict control of the programmer, allowing data-typing kinks to be worked out before the script is put into production. You need to exercise care, however, whenever user input enters the equation.

Look to the NaN value as a debugging aid. If some calculation is failing, use alert dialog boxes to show the values of the operands and components. Any value that reports itself to be NaN means that it has problems at its source that need fixing before your calculation can even get started.

As a point of trivia, the NaN value is, believe it or not, a number data type, and is also a property of the static Number object.

2.2.4 See Also

Recipe 8.2 for numeric data entry validation in a form.