Choose form validation style carefully
In web applications, validation of user input can be done with two
different tools:
-
scripting
code executed by the browser (javascript, for example)
-
regular java code executed by the server, as part of the web application
Server validation:
- cannot be disabled by a change in browser preferences
- executes only after the
SUBMIT
button is pressed
- validates all fields of the form as one unit
- if an error is detected, a new web page is displayed, with an appropriate
error message
Browser validation:
- can be disabled by a change in browser preferences
- can be initiated in two ways : after the
SUBMIT
button is pressed,
or after an input field has changed
- if executing after
SUBMIT
is pressed, the form's data is POST
-ed
to the server only if validation is successful
- if an error is detected, a message is presented to the user
- usually, no second HTTP request is sent to the server; the javascript simply works with the existing page
Another important distinction between the two styles deals not with
their behavior, but with their testability. Validation code on the
server can always be tested economically using tools such as JUnit.
During the entire life of an application, such tests can be quickly repeated
using automated means, helping to identify possible errors caused by code
changes. Although tools such as HttpUnit
can test javascript behavior in web applications, such tests do not seem to be as simple
to implement as JUnit tests on a Model Object.
Browser validation seems most useful for:
- providing a specific user experience
- low bandwidth environments
- forms with a large number of fields, each validated as it's being input
If using scripting, should validation be done after SUBMIT
is
pressed, or as each field is changed? If there are no dependencies between
fields, there is not much difference between the two styles. However, if
there are dependencies between fields, which is quite common, then the
validate-after-SUBMIT
style is likely to be simpler to implement.
Many prefer to treat server validation as mandatory and browser validation
as optional, either as a performance optimization or as the preferred user
experience. If both are implemented, then this will usually represent significant
code repetition.
See Also :