Is there a recommended way to validate form data entered by the user? Should I do it on the client or the server?

Alex Chaffee

[When you show a form (POST or GET) to a user you can check for some required fields in javascript, but you should double check it again on the servlet. I mean, some fields are required, other need to be in a range (too many characters, too little number, NaN, and so on), and other simple checks.

Is there a (more or less) standard way to achieve this?

I'm using an XML config file where I say every argument that every servlet receives, if it's required or not, its type and limits, and so on. I was wondering if there was another way more appropiate to do this.]

> Is there a (more or less) standard way to achieve this?

No. You could create a monstrously complex method using reflection and a list of data types and expected values, but that gets unworkable really quickly. The problem is, you'll have your own types of valid data values, and any library that tries to solve the whole thing will become something like XSchema, which is really complicated and *still* doesn't handle certain common cases.

I always find that when a "config" file format gets too complicated, you may as well throw it away and just use Java as your rules language.

My advice is to just make a method called "validate(HttpRequest)" for each servlet. It can return a null if they're OK and a String with an error message if they're not. The calling doGet() method can print the error message in whatever form is appropriate for your UI (divide and conquer).

public void doGet(...) {
  String error = validate(req);
  if (error != null) {
    printError(resp, error);
  // continue on with processing form

(Alternately, you could throw a ValidationException whose getMessage() field contains the error. My personal style is to avoid exceptions except in truly exceptional cases, and since you expect the user to enter bogus data at least some of the time, this doesn't qualify.)

Then, once you've written a few of these, you will see repeated types of checks -- like "make sure it's really a number" and "make sure it's between a given range." Factor these out into static utility methods, put them into a class (say, FormValidator). Then rewrite your old validate() methods to use these utility methods, and writing new validate() methods will become a little easier next time.

Check Refactoring by Martin Fowler for inspiration on this sort of incremental programming. It's a lot more rewarding and efficient than trying to solve the whole problem all at once.

Also, check Jakarta Regexp package if you're going to be validating string contents.

Please see the forum threads:

for some more discussion of this problem.