version 1.23


Simple and extendable module that allows developers to handle HTML form input validation and display flexibly and consistently.


This module:

  • provides functionality to handle all of the various types of HTML form inputs

  • handles populating form inputs with user entered data or progammer specified default values

  • provides support for validation of user entered input

  • handles presenting customizable error feedback to users

  • should be easy to extend, the WWW::Form module is designed to be inherited from, so you can add your own features

  • Can be used in both mod_perl and CGI environments

The most time consuming part (and it's not too bad) of WWW::Form usage is creating the data structure used for instantiating a WWW::Form object. Once you have a WWW::Form object instance configured, almost all your work is done as it will have enough information to handle a variety of HTML form-related tasks.

Before we get too involved in the details, let's take a look at a sample usage of the WWW::Form module in a typical setting. The following example uses CGI instead of mod_perl, so if you're using mod_perl, certain pieces of the code would look a little different. The WWW::Form module is used the same way in both environments (CGI or mod_perl), though.

A sample usage:

    use strict;
    use warnings;

    use CGI;
    use WWW::Form;

    # Used by WWW::Form to perform various validations on user entered input
    use WWW::FieldValidator;

    # Define values for form input name attributes as constants
    use constant EMAIL_FIELD_NAME => 'emailAddress';
    use constant PASSWORD_FIELD_NAME => 'password';

    # Gets us access to the HTTP request data
    my $q = CGI->new();

    # Hash ref of HTTP vars, would be $r->param() if you're using mod_perl
    my $params = $q->Vars() || {};

    my $form = WWW::Form->new(

    # Check to see that the form was submitted by the user if you're using
    # mod_perl, instead of $ENV{REQUEST_METHOD} you'd have $r->method()
    if ($form->is_submitted($ENV{REQUEST_METHOD})) {

        # Validate user entered data

        # If the data was good, do something
        if ($form->is_valid()) {
            # Do some stuff with params because we know the user entered data
            # passed all of its validation

    # Display the HTML web page
    print <<HTML;
    Content-Type: text/html

    <title>A Simple HTML Form</title>

        # Display the HTML form content
        print $form->get_form_HTML(action => './');

    print <<HTML;

    # Returns data structure suitable for passing to WWW::Form object
    # constructor, the keys will become the names of the HTML form inputs
    sub get_form_fields {
        my %fields = (
            &EMAIL_FIELD_NAME => {
                label        => 'Email address',
                defaultValue => '',
                type         => 'text',
                validators   => [WWW::FieldValidator->new(
                    'Make sure email address is well formed'
            &PASSWORD_FIELD_NAME => {
                label        => 'Password',
                defaultValue => '',
                type         => 'password',
                validators   => [WWW::FieldValidator->new(
                    'Password must be at least 6 characters',
        return \%fields;

Creating WWW::Form Objects

The WWW::Form constructor takes three parameters. The first parameter called $fieldsData, is a hash reference that describes how the form should be built. $fieldsData should be keyed with values that are suitable for using as the value of the form inputs' name HTML attributes. That is, if you call a key of your $fieldsData hash 'full_name', then you will have some type of form input whose name attribute will have the value 'full_name'. The values of the $fieldsData keys (i.e., $fieldsData->{$fieldName}) should also be hash references. This hash reference will be used to tell the WWW::Form module about your form input. All of these hash references will be structured similarly, however, there are a couple of variations to accommodate the various types of form inputs. The basic structure is as follows:

     # UI presentable value that will label the form input
     label => 'Your name',
     # If set, the form input will be pre-populated with this value
     # you could hard code a default value or use a value retrieved
     # from a data base table, for example
     defaultValue => 'Homer Simpson',
     # The type of form input, i.e. text, checkbox, textarea, etc.
     # (more on this later)
     type => 'text',
     # An array ref of various validations that should be performed on the
     # user entered input
     validators => [],
     # A hash ref that contains extra HTML attributes to add to the
     # container.
     container_attributes => {},
     # A hint that will be displayed to the user near the control and its
     # label to guide him what to fill in that control. (optional)
     hint => 'text',
     # A hash ref that contains extra HTML attributes to add to the
     # container of the hint.
     hint_container_attributes => {},

So to create a WWW::Form object with one text box you would have the following data structure:

 my $fields = {
     emailAddress => {
         label        => 'Email address',
         defaultValue => '',
         type         => 'text',
         validators   => [WWW::FieldValidator->new(
             'Make sure email address is well formed
         container_attributes => { 'class' => "green",},
         hint => "Fill in a valid E-mail address",
         hint_container_attributes => { 'style' => "border : double", },

You could then say the following to create that WWW::Form object:

  my $form = WWW::Form->new($fields);

Now let's talk about the second parameter. If a form is submitted, the second parameter is used. This parameter should be a hash reference of HTTP POST parameters. So if the previous form was submitted you would instantiate the WWW::Form object like so:

  my $params = $r->param(); # or $q->Vars if you're using CGI
  my $form   = WWW::Form->new($fields, $params);

At this point, let me briefly discuss how to specify validators for your form inputs.

The validators keys in the $fieldsData->{$fieldName} hash reference can be left empty, which means that the user entered input does not need to be validated at all, or it can take a comma separated list of WWW::FieldValidator objects. The basic format for a WWW::FieldValidator constructor is as follows:

      # Optional, depends on type of validator, if input is entered validation
      # is run, if nothing is entered input is OK

The FieldValidator types are:


So to create a validator for a field that would make sure the input of said field was a minimum length, if any input was entered, you would have:

      'String must be at least 6 characters',
      6, # input must be at least 6 chars
      # input is only validated if user entered something if field left blank,
      # it's OK
      1 # field is optional

Now for the third parameter. The third parameter is simply an array reference of the keys of the $fieldsData hash, but the order of elements in the array ref should be the order that you want your form inputs to be displayed in. This array ref is used by the get_form_HTML method to return a form block that can be displayed in an HTML page.

  # The third parameter will be used to generate an HTML form whose inputs
  # will be in the order of their appearance in the array ref, note this is
  # the constructor format you should use when instantiating form objects
  my $form = WWW::Form->new(
      ['name', 'emailAddress', 'password']

How To Create All The Various Form Inputs

The following form input types are supported by the WWW::Form module (these values should be used for the 'type' key of your $fieldsData->{$fieldName} hash ref):


The following structure can be used for text, password, hidden, file, and textarea form inputs:

  $fieldName => {
      label => 'Your name',
      defaultValue => 'Homer Simpson',
      type => 'text', # or file, password, hidden, textarea
      validators => []

The following structure should be used for radio and select form inputs:

The data structure for input types radio and select use an array of hash references called optionsGroup. The optionsGroup label is what will be displayed in the select box or beside the radio button, and the optionsGroup value is the value that will be in the hash of HTTP params depending on what the user selects. To pre-select a select box option or radio button, set its defaultValue to a value that is found in the optionsGroup hash ref. For example, if you wanted the option 'Blue' to be selected by default in the example below, you would set defaultValue to 'blue'.

  $fieldName => {
      label => 'Favorite color',
      defaultValue => '',
      type => 'select',
      optionsGroup => [
          {label => 'Green', value => 'green'},
          {label => 'Red',   value => 'red'},
          {label => 'Blue',  value => 'blue'}
      validators => []

The following structure should be used for checkboxes:

Note: All checkbox form inputs need a defaultValue to be specified, this is the value that will be used if the checkbox is checked when the form is submitted. If a checkbox is not checked then there will not be an entry for it in the hash of HTTP POST params. If defaultChecked is 1 the checkbox will be selected by default, if it is 0 it will not be selected by default.

  $fieldName => {
      label => 'Do you like spam?',
      defaultValue => 'Yes, I love it!',
      defaultChecked => 0, # 1 or 0
      type => 'checkbox',
      validators => []




version 1.23


WWW::Form - Object-oriented module for HTML form input validation and display


NOTE: All methods are available using internalCapsStyle and underscore_separated_style. So 'isSubmitted' is also available as 'is_submitted', and 'getFieldHTMLRow' is also available as 'get_field_HTML_row', and so on and so forth.

Many convenience methods for displaying HTML form data including form inputs, labels, and error feedback are provided. You do not need to use these methods to display your form inputs, but they should be flexible enough to handle most cases.


Creates a WWW::Form object. $fieldsData is a hash reference that describes your WWW::Form object. (See instantiating a WWW::Form object above.) $fieldsValues (i.e., $params below) has keys identical to $fieldsData. $fieldsValues is a hash reference of HTTP POST variables. $fieldsOrder is an array reference of $fieldsData keys that is used to determine the order that form inputs are displayed in when getFormHTML() is called. If you don't use this parameter you should use the other public methods provided and display your form inputs by hand.


  my $params = $r->param() || {};
  my $form = WWW::Form->new($fieldsData, $params, $fieldsOrder);


Validates field's values input according to the validators (WWW::FieldValidators) that were specified when the WWW::Form object was created. This will also set error feedback as necessary for form inputs that are not valid.

Returns hash reference of all the fields that are valid (generally you don't need to use this for anything though because if all the validation passes you can just use your hash ref of HTTP $params, i.e. $r->param()).


  if ($form->isSubmitted($r->method)) {
      # validate fields because form was POSTed


An alias for validateFields.


Returns hash ref of fields data.


  my $fields = $form->getFields();


An alias for getFields.


Resets values and default values for all fields


  $form->resetFields(include_defaults => 1);


An alias for resetFields.


Returns hash ref of field data that describes the form input that corresponds to the passed $fieldName ($fieldName should be a value of a key in the $fieldsData hash ref you used to construct your WWW::Form instance).


  my $field = $form->getField('address');


An alias for getField.


Returns an array of all the error feedback (if any) for the specified $fieldName.


  my $name_feedback = $form->getFieldErrorFeedback('fullName');


An alias for getFieldErrorFeedback.


Returns array ref of field names in the order that they will be displayed.




An alias for getFieldsOrder.


Returns the current value of the specified $fieldName.




An alias for getFieldValue.


Returns 1 or 0 depending on whether or not the specified field name is valid.




An alias for isFieldValid.


Returns array ref of validators for the passed field name.


  $validators = $form->getFieldValidators($fieldName);


An alias for getFieldValidators.


Returns value of a field's 'type' key for the specified $fieldName.


  my $input_type = $form->getFieldType('favoriteColor');


An alias for getFieldType.


Returns the label associated with the specified $fieldName.


  my $ui_label = $form->getFieldLabel('favoriteBand');


An alias for getFieldLabel.


Returns the hint associated with the specified $fieldName or undef if it does not exist.


  my $hint = $form->getFieldHint('favoriteBand');


An alias for getFieldHint.


Sets the value of the specified $fieldName to $value. You might use this if you need to convert a user entered value to some other value.


  $form->setFieldValue('fullName', uc($form->getFieldValue('fullName')));


An alias for setFieldValue.


Returns true if all form fields are valid or false otherwise.


  if ($form->isSubmitted($r->method)) {
      # validate fields because form was POSTed

      # now check to see if form inputs are all valid
      if ($form->isValid()) {
          # do some stuff with $params because we know
          # the validation passed for all the form inputs


An alias for isValid.


Returns true if the HTTP request method is POST. If for some reason you're using GET to submit a form then this method won't be of much help. If you're not using POST as the method for submitting your form you may want to override this method in a subclass.


  # Returns true if HTTP method is POST
  if ($form->isSubmitted($r->method())) {
      print "You submitted the form.";


An alias for isSubmitted.


Returns a string representation of the current instance.


  &LOG->debug("WWW::Form instance: " . $form->asString());


An alias for asString.


Returns an HTML form input for the specified $fieldName. $attributesString is an (optional) arbitrary string of HTML attribute key='value' pairs that you can use to add attributes to the form input, such as size='20' or onclick='someJSFunction()', and so forth.


  $html .= $form->getFieldFormInputHTML(
      " size='6' class='PasswordInput' "


An alias for getFieldFormInputHTML.


Returns the opening tag of the <td> element that belongs to the label.


Returns the opening tag of the <td> element that belongs to the control.


    $html .=
            'fieldName' => "name",
            'attributesString' => " class=\"hello\"",
            'tr_attr_string' => " class=\"control\"",

This function renders the field HTML row and returns the HTML.


    $html .= $self->renderHintHTMLRow('name');


    $html .= $self->renderHintHTMLRow(
        form_args => {
            hint_container_attributes => {
                class => 'FormBlueBackground'

This function renders the hint HTML row of the specified field and returns the HTML.


        'attributesString' => $attributesString,
        'form_args' => \%form_args,

Returns HTML to display in a web page. $fieldName is a key of the $fieldsData hash that was used to create a WWW::Form object.


attributesString - Optional arbitrary string of HTML attribute key='value' pairs that you can use to add attributes to the form input.

form_args - The parameters passed to getFormHtml(). This function will extract the hint_container_attributes value if it's set. More at renderHintHTMLRow().

The only caveat for using this method is that it must be called between <table> and </table> tags. It produces the following output:

  <!-- NOTE: The error feedback row(s) are only displayed if the field -->
  <!-- input was not valid -->
  <td colspan="2">$errorFeedback</td>


An alias for getFieldHTMLRow.


This method is identical to getFieldHTMLRow() except that it returns an empty string if the field type is "hidden". This method can be used if you are rendering the hidden elements outside the main form table. This prevents hidden inputs from being displayed twice.


An alias for getFieldHTMLRowNoHidden.


Returns HTML error content for each vaildator belonging to $fieldName that doesn't pass validation.

Returns following HTML:

  <div class='feedback'>
  <div class='feedback'>
  <div class='feedback'>

Note: If you use this, you should implement a CSS class named 'feedback' that styles your error messages appropriately.


  $html .= $form->getFieldFeedbackHTML('emailAddress');


An alias for getFieldFeedbackHTML.


Returns an opening HTML form tag.


name - Value of HTML name attribute.

action - Value of action HTML attribute.

attributes - Optional hash ref of HTML attribute name value pairs.

is_file_upload - Optional, boolean, should be true if your form contains file inputs.


      action => '/',
      name   => 'MyFormName',
      attributes => {class => 'MyFormClass'}

Returns HTML similar to:

  <form action='/'


An alias for startForm.


Returns HTML to close form.


  $html .= $form->endForm();


An alias for endForm.


Loops through the fieldsOrder array and builds markup for each form input in your form.

Returns HTML markup that when output will display your form.

This method outputs a basic form layout that should be reasonably useful "out-of-the-box". If you have more complex form presentation requirements you may use the various HTML display methods to customize your form's presentation. Subclassing may also be useful for customizing form displays.


action - Value of form's action attribute.

name - Value that will be used for form's name and id attribute.

attributes - hashref of key value pairs that can be used to add arbitrary attributes to the opening form element.

submit_label - Optional label for your form's submit button.

submit_name - Optional Value of your submit button's name attribute. This value will also be used for your submit button's id attribute.

submit_type - Optional string value, defaults to submit, if you want to use an image submit button pass submit_type as 'image'.

submit_src - Optional unless submit_type is 'image' then an image src should be specified with submit_src, e.g. submit_src => './img/submit_button.png'.

submit_class - Optional string that specifies a CSS class.

submit_attributes - Optional hash ref of arbitrary name => 'value' HTML attributes.

is_file_upload - Optional boolean that should be true if your form contains a file input.

hint_container_attributes - Optional HTML attributes for all the table rows containing the hints.

buttons - Use this if you want your form to have multiple submit buttons. See API documentation for getSubmitButtonHTML() for more info on this parameter.


  print $form->getFormHTML(
      action => './',
      name => 'LoginForm',
      attributes => {
          class => 'FormBlueBackground'
      submit_label => 'Login',
      is_file_upload => 1


An alias for getFormHTML.


Returns HTML to render all hidden inputs in the form.


An alias for getHiddenFieldsHTML.


Used by get_form_HTML to get HTML to display a type of a submit button.

Returns string of HTML.

Arguments: submit_type - 'submit' or 'image', defaults to 'submit' if not specified.

submit_src - If type is 'image', this specifies the image to use.

submit_label - Optional label for the button, defaults to 'Submit'.

submit_class - Optional value for class attribute.

submit_attributes - Optional hash ref of name => value pairs used to specify arbitrary attributes.

buttons - Optional, array reference of hash refs of the previous arguments. You can use this parameter if you want your form to have multiple submit buttons.


An alias for getSubmitButtonHTML.



To see some demos of WWW::Form and WWW::FieldValidator point your web browser to:


The following modules are related to WWW::Form and WWW::FieldValidator, you might want to check them out.






Ben Schmaus

If you find this module useful or have any suggestions or comments please send me an email at


July 2, 2003

Code formatting and cleanup.

Adds support for file inputs.

July 3, 2003

Adds code examples to documentation for public methods.

September 25, 2003

Adds new methods including: resetFields(), isFieldValid(), and getFieldValidators().

Changes _setFields method to handle empty user values. That is, in previous releases, if a form is submitted and the value for a field is empty, the value of the field will be set to the field's default value if it has one. This release updates _setFields to prefer submitted values over default values.

Fixes some pdoc stuff.

September 26, 2003

More pdoc changes.

January 10, 2004

Adds support for displaying multiple submit buttons.

Adds new public method: getSubmitButtonHTML.

Adds support for escaping the value of HTML input 'value' attributes.

January 5, 2005

Adds README file to distribution.

Makes some minor documentation changes.

March 29, 2005

Merged the changes from the repository.

Fixed the MANIFEST.

June 8, 2006

Updates docs.

Adds new methods for dealing with hidden form inputs.

November 18, 2006 - WWW::Form 1.17

Adds support for select boxes with 'multiple' attribute set. Note that this needs to be tested in a mod_perl environment.

Fixed CondTestMore to adapt it to the new Test::More.

Removed in favor of t/00-load.t.

Moved the modules under lib/ to improve the kwalitee.

Moved CondTestMore under t/lib (kwalitee).

Moved to the examples/ directory (kwalitee.)

Added a LICENSE section to the PODs.

Added t/pod.t (kwalitee).

Added t/pod-coverage.t and made the POD have full coverage (for the kwalitee.)

August 23, 2008 - WWW::Form 1.18

Added a rudimentary test to test for valid emails.

Fixed .


Add more helpful error logging.

Give this module a better namespace?

Extension Ideas

Write a subclass that supports a templating library like Text::MicroMason or Text::Template.

Add functionality for generating and performing client side validation.


Thanks to Shlomi Fish for suggestions and code submissions.


Please report them. :)

Bug reports can be filed at:

Or you can send email to perlmods at benschmaus dot com.


WWW::Form source code can be obtained via anonymous svn access at:


This program is free software. You may copy or redistribute it under the same terms as Perl itself.


Shlomi Fish <>


This software is copyright (c) 2003 by Benjamin Schmaus.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.


Shlomi Fish <>


This software is copyright (c) 2003 by Benjamin Schmaus.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.