Digital Elephant Productions

Form Checking

A form presented to a client can be filled in without many constraints; the resulting set of data must be checked for correctness. This is especially important when the contents are destined to be saved in a database; one of the banes of database administrators is keeping their data clean.

In principle, there are two places to check the field contents: in the browser (using JavaScript), or in the server. Most of the time, I believe that having the server do the checking is preferred, because it must do the checks anyway, to protect itself against malicious HTTP request strings, which may be intentionally malformed. The drawback of this choice is that, unless we build in AJAX interactions, all the checking and error feedback is deferred until the client sends the entire form to the server. For simple forms, this is not a big problem, but for forms with many fields, it is often a good idea to validate each field as it is completed. To avoid duplication of code, this validation can be done by the server (which will have to have validation code anyway), using an AJAX transaction triggered from a field completion event.

There are two other cases where browser-side checking might also be in order. First, if the value of one field should cause different behaviour in other fields, then JavaScript checking (and subsequent action) is usually needed. Usually, a JavaScript function will be invoked as an onBlur event attached to the field it should check. (One might also use onChange as the event.) Second, if a check is likely to take a significant amount of time (eg, validating a URL), it is often a good idea to send a separate AJAX request to the server as a result of a field completion event, so that the checking can take place while the client is filling out the rest of the form.

User feedback about errors found in fields can come in two ways: the offending fields may change color, or error messages may appear, indicating what needs to be corrected. I favor doing both; the highlighted fields draw the client's attention, and the explanation can then be put in a convenient place on the form, rather than being constrained to appear close to the offending field.

Last updated January 19, 2007 Webmaster