Validating that a required form field is a number

You can test a string with the parseInt() and parseFloat() methods. However, these methods have a peculiar behavior. If a string starts with a number, the methods will accept all leading characters that are numbers and discard the rest:

parseInt(3abc) returns 3     = is a number
parseInt(3.1abc) returns 3.1 = is a number

However, if the first character is a letter, it will create an error

parseInt(abc3.1) returns NaN = Not a Number

Javascript contains a method that does the number test for you, isNaN(number). If the value passed to the method is not a number, it will return true.

Example:

Enter test:

The code:

<script type="text/javascript">
<!--

function isNumber(field)
{
  if (!isNaN(field.value))
  {
    alert("You entered number: " + field.value + ".");
  }
  else
  {
    alert("This field is not a number.");
    
    field.focus();
    field.select();
    field.value = "";
  }
}
  
// -->
</script>