CGI::ValidOp(3) Simple validation of CGI parameters and runmodes.

SYNOPSIS


# given the following CGI parameters:
# op=add_item; name=William Blake; ssn=345-21-6789; crackme=$ENV{EVIL_MEAT};
use CGI::ValidOp;
my $cgi = CGI::ValidOp->new({
add_item => { # using full syntax
name => {
label => 'Name',
checks => [ 'required', 'text::words' ],
},
ssn => {
label => 'Social Security number',
checks => [ 'demographics::us_ssn' ],
},
},
remove_item => { # using shortcut syntax
ssn => [ 'Social Security number', 'required', 'demographics::us_ssn' ],
confirm => [ 'Confirmation checkbox', 'required', 'checkbox::boolean' ],
},
cgi_object => new CGI($fh),
});
my $name = $cgi->param( 'name' ); # eq "William Blake"
my $ssn = $cgi->param( 'ssn' ); # eq "345-21-6789"
my $crackme = $cgi->param( 'crackme' ); # is undef; it was removed by the check
my $confirm = $cgi->param( 'confirm' ); # is undef; it doesn't exist
my $op = $cgi->op; # eq "add_item"
my @errors = $cgi->errors; # eq ( 'Parameter "crackme" contained invalid data.' )
my %vars = $cgi->Vars; # eq (
# name => "William Blake",
# ssn => "345-21-6789",
# crackme => undef,
# )

DESCRIPTION

CGI::ValidOp is a CGI parameter validator that also helps you manage runmodes. Its aims are similar to Perl's: make the easy jobs easy and the complex jobs possible. CGI parameter validation is boring, and precisely for that reason it's easy to get wrong or ignore. CGI::ValidOp takes as much of the repetition as possible out of this job, replacing it with a simple interface.

Unique features

There are many CGI parameter validation modules on CPAN; why on earth would I write another one, and why should you use it? Before writing ValidOp I made a list of requirements and checked all available modules against it, hoping that even if nothing matched there'd be a project which I could subclass or contribute to. I didn't find anything. Here's what I think ValidOp does right:
Simple API.
Minimal usage is useful.
Easy to add new checks.
Relation of parameters to run-modes/operations.
In addition to validating parameters, CGI::ValidOp has a number of methods for dealing with runmodes (henceforth referred to as 'ops'). In fact, the 'op' concept is key to ValidOp's advanced usage: parameters are defined as children of ops. A ``display_item'' op may need only a numeric id, while an ``add_item'' op will take several parameters. All these can be defined once in a single location.
Validation defaults settable on many levels to minimize repetition.
You can change the validation defaults for the entire app, all parameters for one runmode, or per-parameter.
CGI integration and compatibility.
Parameters can be accessed just like with CGI.pm: param for individual parameters and Vars for all of them.
Per-parameter error messages.
While error message must be available globally, having per-parameter error messages is an important usability improvement. When returning a long form page to a user, it's good to show them error messages where they're most useful.
OO and test-driven
ValidOp is test-driven, object-oriented Perl.
Extensive and public test suite.
If you're going to trust someone else's code for security purposes it's nice to have proof that it works. CGI::ValidOp has an extensive test suite that checks every part of its operation, particularly the validation routines. I keep the current version running at <http://sonofhans.net> validop with a full test page. If you can produce unexpected output, file a bug report.

METHODS

new( \%options )

Creates and returns a new CGI::ValidOp object. The initializing hashref is optional. If supplied, it may contain two types of values: configuration options and runmode definitions. Configuration options must be prepended with a dash ("-"); runmodes must not be.

Setting 'cgi_object' will allow you to override the CGI object that would be provided by default, if say, you needed to use this module under mod_perl.

    my $cgi = CGI::ValidOp->new({
        -allow_unexpected => 0,     # configuration option
        add => {},                  # op, or runmode definition
    );

See Configuration and ``Runmode Management'' for more details.

param( $name, \@checks )

"param" behaves similarly to the CGI.pm method of the same name, returning the value for the named parameter. The differences from CGI.pm's "param" are:
  • The return value will be validated against all defined checks.
  • The return value will be untainted if the checks require it.
  • Any necessary error messages will be created.

The "\@checks" arrayref is optional. If supplied, it replaces all previously defined checks for the parameter and overrides all defaults. An empty arrayref ("[]") will give you the parameter as input by the user, unchecked; it will still be tainted.

Vars

"Vars" behaves similarly to the CGI.pm method of the same name, returning the entire parameter list. In scalar context it returns a hash reference; in list context it returns a hash. The differences from CGI.pm's "Vars" method are:
  • Multivalue parameters are returned as an arrayref, rather than a null-byte packed string.
  • The runmnode_name parameter (``op'' by default) is not returned; see op for more details.
  • Unexpected parameters are not returned (see allow_unexpected).
  • Parameters that failed one or more checks are returned as "undef".
  • In scalar context the hashref is not tied, and changes to it do not affect the parameter list.

op

Returns the current runmode name. In the normal case, this is the CGI parameter given for ``op'' (but see runmode_name). Several factors affect the return value:
  • If a runmode parameter is given but it doesn't match the name of any defined runmode, ``runmode aliases'' are searched.
  • If no ``runmode alias'' matches, the value of default_op is returned.

Note that while ValidOp doesn't require you to use its runmode management features, it still uses them internally. Even in the of no defined parameters or runmodes, ValidOp uses ``default'' as its runmode and all parameters are subsidiary to it. This is invisible to the user.

errors

Returns an arrayref of all error messages for the current parameter list and parameter definitions. Returns "undef" if there are no errors.

Op( $op_name )

Returns the CGI::ValidOp::Op object for the current runmode, or the runmode given. See ``Op Objects'' for more details, or the documentation for CGI::ValidOp::Op for all the details.

set_vars( \%params )

Resets the parameter list to the given hash reference.

CONFIGURATION

ValidOp has a number of configurable options which alter its behavior. These options can be given in the constructor, via accessor methods, or both:

    my $cgi = CGI::ValidOp->new({
        -allow_unexpected   => 0,
        -default_op         => 'home',
    });
    
    $cgi->default_op( 'view' );  # overrides 'home' above

allow_unexpected

Default: 1. Accepts: 1 or 0. Controls whether ValidOp accepts incoming CGI parameters which you have not defined. If true, all incoming parameters are accepted and validated. If false, parameters you have not defined are ignored.

return_only_received

Default: 0. Accepts: 1 or 0. If true, will not return any data for a parameter not received in the query string. ValidOp's default behavior is to return an "undef" value in this situation.

default_op

Default: 'default'. Accepts: word. The default runmode name. If no runmode parameter is given, or if the runmode given does not exist, the runmode specified here will be used. See ``Runmode Management''.

disable_uploads

Default: 1. Accepts: positive integer. Passed through to CGI.pm when getting parameters. See CGI.pm.

error_decoration

Default: undef. Accepts: array. Text with which to surround parameter labels in error messages. If given a single scalar, it is inserted both before and after the label. If given an arrayref, the first value is inserted before and the second is inserted after.

Given an error message of "$label is required." and a label of ``Confirmation checkbox,'' ValidOp would normally output "Confirmation checkbox is required.". Here's how various values affect the error message:

    $cgi->error_decoration( '"' );
    # "Confirmation checkbox" is required.
    $cgi->error_decoration( '* ', undef );
    # * Confirmation checkbox is required.
    $cgi->error_decoration( undef, ':' );
    # Confirmation checkbox: is required.
    $cgi->error_decoration( '<strong>', '</strong>' );
    # <strong>Confirmation checkbox</strong> is required.

post_max

Default: 25,000. Accepts: positive integer. Passed through to CGI.pm when getting parameters. See CGI.pm.

runmode_name

Default: 'op'. Accepts: word. The name of the runmode. ValidOp treates the runmode parameter differently from other parameters; see ``Runmode Management'' for more details.

on_error_return...

These routines control what values are returned by "Vars()" and "param()". They are mutually exclusive, and have the following order of precedence:
  • on_error_return_undef
  • on_error_return_encoded
  • on_error_return_tainted

In other words, if both "on_error_return_undef" and "on_error_return_tainted" are given as true, "on_error_return_undef" will apply.

on_error_return_undef

The default behavior. Values which fail validation are ignored, and returned as "undef".

on_error_return_encoded

Values which fail validation are returned as input, but first encoded with HTML::Entities's "encode()" method.

on_error_return_tainted

Values which fail validation are returned unchanged. Don't do this.

Defining Checks

ValidOp checks
When constructing a CGI::ValidOp object, you may pass a "-checks" option. The default checks are: "['text']".
Op checks
When defining an op within the CGI::ValidOp constructor, you may pass a "-checks" option.
Parameter checks
When defining a param within the op definition, you may pass a "-checks" option.
On-the-fly checks
When calling the "param" method, you may pass an array reference as the second parameter. This arrayref is passed straight through to the parameter's "checks" accessor.

COPYRIGHT

Copyright (c) 2003-2005 Randall Hansen. All rights reserved.

This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself.

See http://www.perl.com/perl/misc/Artistic.html

AUTHORS

Randall Hansen <[email protected]>

Chad Granum <[email protected]>