Database

Using XML Schema for Validating User Input

By Alex C. Punnen, January 02, 2008

Capturing and validating user input

Alex is a technical lead for the Nokia Siemens Network. He can be contacted at alexcpn@gmail.com.

One of the often repeated (and mundane) tasks in software development is capturing and validating user input. Nevertheless, these are important tasks, and the most common method of accomplishing them is with if-else statements in the code. However, this approach leads to code bloat and inflexible code, not to mention it is hard to unit test.

Another approach is to use something like the Apache CLI (Comand-Line Interface), although here the fields and parameters have to be input in the code, again leading to inflexible code and situations where the parameters or acceptable range/values changes have to be updated and recompiled.

However, using an XML Schema for validation decouples the code from the validation task completely. For example:

1. The user enters a command via the GUI/CLI to create a "route" between two "servers":

No code required for validation, (only for forming the XML and calling the xerexes API for validation).

New command-line interface commands can be added without adding any code.

The formed XML can be used to extract user inputs.

Now let's see how you can do this using Java. Here, I illustrate the same approach by getting the input from the command line. The command-line input follows the pattern fieldname<space> value; and use pattern matching via regular expressions to extract the fields. Listing Two is an excerpt of the main method:

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task.
However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

This month's Dr. Dobb's Journal

This month,
Dr. Dobb's Journal is devoted to mobile programming. We introduce you to Apple's new Swift programming language, discuss the perils of being the third-most-popular mobile platform, revisit SQLite on Android
, and much more!