Example - Field Validation & Formatting

This example shows how to format and validate a telephone number field on an Add or Edit screen layout.

The example involves a single field named tel_number. Data in the form of numbers entered into this field will automatically be formatted in the usual form of a telephone number in the USA. For example, entering the digits 1234567890 will result in a display of (123)456-7890. In addition, the function will not allow any non-numeric characters to be entered unless the user acknowledges that this is what they want.

To set up this requirement, take the following steps –

  • Within the data dictionary, define the field TEL_NUMBER with a display type of Text Field
  • Make sure you give these fields read and write permission
  • Place this field on an Add screen layout. Add an HTML modifier to this field. The modifier value should be onkeypress=formatAsPhoneNumber(this);
  • Place the following JavaScript functions within the UserJavaScript.js file.
    function chkNAN(char2chk)
    {
       var validNum = "0123456789";
       if (validNum.indexOf(char2chk) == "-1")
          return(confirm("You have entered a non-numeric 
                          character.\nDo you want to turn off non-
                          numeric character checking?"));
    }
    
    function formatAsPhoneNum(fld)
    {
       var isNamedFone = false;
       fldVal = fld.value;
    
       var tmpStr = "(";
       keyCount = fldVal.length;
       keyEntered =fldVal.substring(keyCount-1,keyCount);
    
       if (keyCount < 2)   isNamedFone = false;
       if (!isNamedFone)   isNamedFone = chkNAN(keyEntered);
    
       keyCount++;
       with (document.editForm)
       {
          switch (keyCount)
          {
             case 2:
                tmpStr +=  fldVal;
                fld.value = tmpStr;
                break;
             case 5:
                fld.value +=  ")";
                break;
              case 9:
                fld.value += "-"; 
                break;
          }
       }
    }
  • When the user enters the telephone number in the field it will be validated, and the formatting applied to the number. If they enter an invalid character, they will see a dialog box with the message You have entered a non-numeric character. Do you want to turn off non-numeric character checking?