MSc-IT Study Material
June 2010 Edition

Computer Science Department, University of Cape Town

Testing for numeric fields

Let us assume that only digits are permitted for the telephone number field (with no spaces, or dashes or parentheses for now). Some examples of valid telephone numbers are:

    44181362500
    002356487
    56478303

Any entry that contains non-numeric values should be considered invalid; the user should be informed of this, and the form should not be submitted.

We can create a useful function notNumeric() that returns true if an argument passed to it is not a number. To write the function we can make use of the special value returned by JavaScript when the result of an attempt to perform a numeric expression is not a number: JavaScript evaluates such expressions to the String "NaN". Our function can be written as follows:

      function notNumeric( fieldString )
      {
      if ( String(fieldString * 1) == "NaN")
      return true;
      else
      return false;
      }
    

We can use this function to extend the validate() function to now only return true if the telephone number consists of digits:

      function validate()
      {
      // at this point no invalid fields have been encountered
      var fieldsValid = true;
      // test field firstName
      if ( isEmpty( orderform.firstName.value ) )
      {
      alert( "First name must have a value - form not submitted" );
      fieldsValid = false;
      }
      // test field familyName
      if ( isEmpty( orderform.familyName.value ) )
      {
      alert( "Family name must have a value - form not submitted" );
      fieldsValid = false;
      }
      // test field telephone
      if ( notNumeric( orderform.telephone.value ) )
      {
      alert( "Telephone number must consist of nothing but digits -
      form not submitted" );
      fieldsValid = false;
      }
      // return Boolean valid fields status
      return fieldsValid;
      }
    

So if a telephone number of "abc" is entered:

the browser will display the following alert window (and not post the form):