# Tutorial 12 - Smart Forms Tutorial 11 - Form Validation - Tutorial 13 - Getting The Bugs Out Smart or intelligent forms automate many repetitive tasks that we meet within our work or hobbies. These tasks can be as simple as altering case or as complex as reformatting or encrypting files. Many smart forms involve arithmetic operations (order forms or metric converters are examples). Although not as glitzy as animation, data manipulation is the type of task a real programmer does often. Smart forms differ from submission forms in that they do not communicate with other sites. All processing is done on the user's computer and thus offers more security. ## Validating Numeric Data Many smart forms involve mathematics so numeric input must often be verified before continuing. JavaScript's built-in function Number() and internal methods (such as isNaN(), parseInt(), parseFloat(), etc.) work well for validating decimal based numbers. However they are incomplete for other radix systems and you will have to gather together your own set of functions to paste into projects. A simple brute force validator solution is to test each character of the entry string for permitted values. Binary integers are limited to 0's and 1's. Octal numbers can have only the characters from 0 to 7. Hexadecimal codes can contain the digits 0 to 9 and the letters A to F (either upper or lower case) only. The following is an example of a hexadecimal entry checker. With suitable changes to the characters allowed and perhaps a length control (fixed or maximum) this code can be reused in many validation situations. The steps are: Make sure there is something to check! Since uppercase letters are more common, be sure to uppercase the string. Or you could include both cases in the character scan. Finally do a simple character by character check for valid characters. In this test invalid or null hexadecimal string will display an error message and return a false value. If the whole string passes the check an ok! message is displayed and a true value is returned. Often these validating functions are written without display messages, leaving it up to the calling function. One last variation is to accept a second parameter which represents whether a message is to be displayed.
    function isHex(entry) {
    validChar='0123456789ABCDEF'; // characters allowed in hex
    strlen=entry.length;          // how long is test string
    if (strlen < 1) {alert('Enter Something!');return false;} // no check!
    entry=entry.toUpperCase();          // in case of lowercase characters
    // Now scan string for illegal characters
    for (i=0; i < strlen; i++ ) {
        if (validChar.indexOf(entry.charAt(i)) < 0) {
           alert("Entry must be in hexadecimal format!");
           return false;
           }
        } // end scanning loop
    alert('ok!'); return true;
    }
Hexcode String Test Once you know for sure that a variable is a number, then you can use the Math object methods parseInt() and parseFloat() to make them into the appropriate type if required. Using parseInt() and parseFloat() by themselves may cause unexpected problems as they can truncate some nonnumeric strings and yield a number as an answer (eg. 1st.). isNaN() is a function to test for numbers but it is limited to decimal values only. ## Multiple Field Validation In many situations the same type of validity check has to be repeated over many fields. One simple method is to use the fact that if the name attribute is reused for several similar controls, an array is automatically set up to give unique pointers to each control value. Note: To convert this form to one that is submitted to a server for script processing change the HTML form element's method to get, the enctype to multipart/form-data and redirect the action to the appropriate URL. Testing Dynamic Names
Each entry box must be filled in with a single digit, no alpha or punctuation or blanks allowed prior to submission. Note how the focus moves to first blank box but user can refocus if desired.
Field one |
Field two |
Field three |
    function verify(id) {  // check entries for single digit values only
    for (idx=0;idx<6;idx++) { // if any field is blank, set focus to it
       obj=document.getElementById(id+idx);temp=obj.value;
       if (temp==="") {obj.focus();return false}
       if (isNaN(parseInt(temp))) {
           alert ('Entry must be a number!');obj.value="";obj.focus();
           return false;}
       }
    return true;}
## Order Forms Smart forms add internal computational methods to a standard form. Examples include order forms (with extended prices, totals, taxes and handling charges), tax forms and commercial forms. Note: Refer to form design for some basics. A start on a simple order form is given and you are encouraged to 'flesh it out' with: some simple math for first line. UGH! automatically update the line after changes. assume that any null entry implies null display. add totaling operation. add tax line including round off to pennies. complete with grand total line. Refer back to multiple field validations for the technique for handling many line items. Sample Order Form
Item Description | Quantity | Unit Cost | Extension
--- | --- | --- | ---
| @ | = |
| @ | = |
Subtotal: |
Tax: |
Total: |
Major project extensions: This order form could be turned into a major project by adding shipping and handling charges and checkboxes for non-taxable items. Or perhaps select boxes for product that when chosen, fill in the unit cost field (preventing the need for some error checks. A long term project could contain item descriptions (perhaps even images) with checkboxes. A checked box places the item on the order form. This may include the quantity level which is echoed to the form. ## Health Checkup Form Body Mass Index Calculator
Weight in pounds: | In kilos:
Height in inches: | In metres:
Body Mass Index [Wgt(Kg) / Hgt(m)2]:
A Body Mass Index of more than 25 indicates that you are overweight. A BMI factor of 30 or more indicates obesity. Being overweight can cause many health problems such as heart disease, strokes and diabetes. And if you should live long enough there is an increased chance of Alzheimer's. Just a word to the wise. ## Text Analysis and Formatting Word count analysis require breaking up (ie. parsing) the source text into words (ie. tokens) that are terminated (ie. delimited) with spaces or punctuation. Fortunately JavaScript has the built-in string method split() which breaks a string into array items based on a delimiter symbol. The CountWords function in the head section of this document shows how the text is first prepared by adding leading/lagging spaces and changing other white space into plain space by using the string method replace(). Then the split() method with space as its delimiter is used to place all the 'words' into an array called splitString. The length of this array is the number of words in the text. Word Count Utility
NOTE: You must view the source code for the CountWords() function! Concordance is the counting of each occurrence of each word and providing the results in a table fashion either sorted by alpha or sorted by most frequently used. This type of utility quickly leads to a spellchecker. Text formatting can be as simple as changing case or initializing all words or first words in sentence. More complex forms of formatting would be to add or remove database tagging. Major project extensions: A document analyzer could be built using a textarea for input. See the JSlint utility for an example. For someone's major project an HTML document could be scanned and all obsolete elements reported. At the same time any HTML ?style? attributes could be flagged and appropriate CSS style properties indicated. This type of project should suit the zealot for modern coding techniques!! A mega project would involve correcting the document and generating a stylesheet for it. Tutorial 11 - Form Validation - Tutorial 13 - Getting The Bugs Out Copyright (c) 2005 by John W. M. Russell