Validating Web forms with Perl

by Mark Stosberg
This file last modified


screenshot of validated form

One of the most frequent uses of Perl in my job is to validate web-based forms. Here's some explanation and sample code to how I do that efficiently and effectively.

As a foundation, I use the CGI::Application framework. I originally thought using a "framework" for simply displaying and validating a form as overkill. I now realize it's not.

First, you'll notice how concise the code is. There is very little overhead with CGI::Application. CGI::Application also helps with re-usability by moving all code into modules. This maximizes code re-us across projects, saving time in the long run.

The heavy lifting for the form validation will be done by Data::FormValidator. The example I've given here is faily simple. Data::FormValidator helps with validating much more complicated cases as well.

This solution may require installing these modules on your server, as well as CGI::Application::Plugin::ValidateRM and the dependencies of these modules.

If these modules aren't already installed on your system, and you don't have root access, you can still install and use them in your own directory by including something like this in the installation process:

perl Makefile.PL LIB=/home/user/perllib \
        INSTALLMAN1DIR=/home/user/man/man1 \
        INSTALLMAN3DIR=/home/user/man/man3 \
        INSTALLBIN=/home/user/bin \
        INSTALLSCRIPT=/home/user/scripts   

Of course, you'll need to include a line like use lib ('/home/user/perllib'); once you've done this.

Setting up the templates

To get this tour started, let's first set up a template with a form to validate. To make it interesting, we'll have a required field, some optional fields, a field that is required if another one is filled in, one with a generic validation constraint, and one with a custom validation constraint.You can view the source of example.tmpl, or go ahead and try out the demo. Some browsers may render example.tmpl as HTML. You can also right-click it and select "Save target as..."

Writing the Perl code

The next step is to write the code that will display the form and validate it's contents. This is probably better explained by direct example than description, so you can view the code I use:

For a long time I did form validation without these extra modules, and I find that this system is much faster, and produces a better user interface by showing the errors on the same page where the user can correct them.

If you have ideas about how this system could be further improved, I'm interested to hear them. Thanks and good luck!

Further resources

You may also be interested in the Data::FormValidator::Tutorial.


Mark Stosberg
Valid CSS! Valid XHTML 1.0!