HTML Markup | JavaScript | Java | Home & Links

Tutorial 11 - Control Validation

Data validation routines test for required or invalid numeric or character strings. Tests can be for specific values, a range of accepted values or a pattern of an acceptable format. The best method of form validation is to use form controls that restrict value selection to known pretested quantities such as radio buttons, check boxes and select lists. When these controls are not appropriate, allow freeform input of data and then validate the entries. Common forms of feedback are: placing the cursor at the invalid entry, highlighting, asterisking, or opening a dialog box with hints as to possible cause or solution.

Common Validations

Freeform controls require many types of common validations such as:

However do not make any false assumptions in what the entry will be. Assuming that age:14 children:3 is in error may require checking the state address ;-] Some common validation mistakes seen on entry forms are:

Validating Numeric Data

Numeric input must always be validated before use. isNaN(), Number(), parseInt(), parseFloat() can be used to check decimal based numbers but badly formatted entries will cause difficulties. And these methods are incomplete for other radix systems. You should create or gather your own set of validating functions.

A brute force solution is to test each character of the entry string for permitted values. Natural numbers have only digits. Integers can also have a leading plus/minus sign. Binary integers are limited to 0's and 1's. Hexadecimal codes only have the digits 0 to 9 and the letters A to F (either upper or lower case).

The following is an example of a hexadecimal entry checker. This code can be reused in many validation situations with suitable changes to the characters allowed and perhaps a length control (fixed or maximum). The steps are:

  1. Make sure there is something to check!
  2. Be sure to uppercase the string being tested.
  3. Do a simple character by character check for valid characters.
  4. Return false if the test string is invalid or null. Option: Display an error message.
  5. Return true if the test string is valid. Option: Display an ok! message.

Validating functions often let the calling function display error messages. A variation would be to accept a parameter which flags if error message display is to be made by validator.

Hexcode String Test  

Once you know for sure that a string is a number, then you can use the Math object methods parseInt() and parseFloat() to make them into numeric type if required. Using parseInt() and parseFloat() by themselves may cause unexpected problems as they can truncate some non-numeric strings and yield a number as an answer (eg. 1st.).

Validating String Data

One example of string data validation is a field that holds a person's surname and is a mandatory field. A first approach could check for an empty string. That is a start but surely a person's last name is at least two characters long. And only a few punctuation symbols (such as hyphen and apostrophe) should be allowed and no digits please! Two other examples of brute force validation are e-mail addresses and postal codes.

String object methods and properties make brute force checks easy. And loosely typed variables are temporarily changed to objects (using wrappers) so that object methods can be used on them as well.

Regular expressions validation is more elegant and much easier than the brute force technique once you master the syntax. It is well worth the effort to learn how to use them if your scripts rely heavily on input validation.

Form Validation

The onsubmit event can be used to call a function to check all fields that require validation before sending a form. The values to be checked (or perhaps the entire form) are passed as parameters. The validation function must return a true if ready to submit or a false if not ready. It also makes sense to use dialog boxes to indicate the nature of the error. An example of a simple call to a validating function is:

<form id="SurveyForm" action=""
      method="post" onsubmit="return validate(f1,f2);"></form>

An alternative method uses a simple button with an onclick event. Either the submit action is suppressed by placing onsubmit="return false;" in the form element or removing the form element altogether!

<form id="foo" action="?" method="post" onsubmit="return false;">
. . .
<input value="Check Form!" onclick="validate(f1,f2);"/>

Field Validation

Many forms are best validated on a by entry basis. The onchange event can call a function to validate an entry box content when you move off the entry box and that entry has changed. Another event that can be used is the onblur event which occurs whenever an element loses focus. Note: Endless loops occur when both blur and focus events are used on several elements. Avoid using focus when using blur.

The example brings up an alert dialog if the correct word is not entered. The entry is checked when you click on a new entry field or another spot in your window or use the tab key to move off the entry. The onclick event suppresses other key clicks. Note that the validation is case insensitive. Look for the isit() routine in the script.

Input the word STOP in the following entry box:
Then click somewhere outside of the box to test!
Input the word STOP in the following entry box:<br>
Then click somewhere outside of the box to test!</td><td>
<input id="i1" type="text" value="" onblur="isit('i1','STOP');return true;">

Keystroke Validation

Do you want to restrict specific characters from being entered into a control. Do you want some form of on-the-fly reformatting. Have you ever been stung by a textarea that let you enter data and then when submitted you were told that only ### characters are allowed. Did you ever wish that the recommendation had defined a maxlength attribute for the textarea control. Each of these situations requires catching individual keystrokes with one of the keystroke events (onkeydown, onkeyup, onkeypress).

This example uses an onkeyup HTML attribute to place a limit on the number of characters allowed in a textarea as well as eliminating unwanted ones. The initCount('txtAreaId',maxChar,'dspAreaId','chkStr') method must be called in the body onload="" element for each textarea to be controlled. The routine also returns a display of the number of characters remaining! If this display is NOT to be shown, use the keyword 'NOSHOW' instead of an actual element id. Check the tutorial on regular expressions for the correct syntax for unwanted characters testing in the chkStr parameter. Use 'NOCHECK' if you do not want any character checking.

Uses initCount() and taCount() functions in source code.

You have ? characters remaining!

JR's HomePage | Comments [jstutorb.htm:2014 07 12]