man Data::FormValidator::Constraints () - Basic sets of constraints on input profile.


Data::FormValidator::Constraints - Basic sets of constraints on input profile.


 use Data::FormValidator::Constraints qw(:all);

In an Data::FormValidator profile:

    constraint_methods => {
            email       => email(),
            fax         => american_phone(),
            phone       => american_phone(),
            state       => state(),


These are the builtin constraints that can be specified by name in the input profiles.

Be sure to check out the SEE ALSO section for even more pre-packaged constraints you can use.

Checks if the email LOOKS LIKE an email address. This should be sufficient 99% of the time. Look elsewhere if you want something super fancy that matches every possible variation that is valid in the RFC, or runs out and checks some MX records.
This one checks if the input correspond to an american state or a canadian province.
This one checks if the input is a valid two letter abbreviation of an american state.
This checks if the input is a two letter canadian province abbreviation.
This constraints checks if the input is an american zipcode or a canadian postal code.
This constraints checks if the input is a valid Canadian postal code.
This input validator checks if the input is a valid american zipcode : 5 digits followed by an optional mailbox number.
This one checks if the input looks like a phone number, (if it contains at least 6 digits.)
This constraints checks if the number is a possible North American style of phone number : (XXX) XXX-XXXX. It has to contains 7 or more digits.
This constraint references the value of a credit card type field.
 constraint_methods => {
    cc_no      => cc_number({fields => ['cc_type']}),
The number is checked only for plausibility, it checks if the number could be valid for a type of card by checking the checksum and looking at the number of digits and the number of digits of the number. This functions is only good at catching typos. IT DOESN'T CHECK IF THERE IS AN ACCOUNT ASSOCIATED WITH THE NUMBER.
This one checks if the input is in the format MM/YY or MM/YYYY and if the MM part is a valid month (1-12) and if that date is not in the past.
This one checks if the input field starts by M(asterCard), V(isa), A(merican express) or D(iscovery).
This checks if the input is formatted like an IP address (v4)


Data::FormValidator also includes built-in support for using any of regular expressions in Regexp::Common as named constraints. Simply use the name of regular expression you want. This works whether you want to untaint the data or not. For example:

 use Data::FormValidator::Constraints qw(:regexp_common);

 constraint_methods => {
        my_ip_address => FV_net_IPv4(),

        # An example with parameters
        other_ip      => FV_net_IPv4(-sep=>' '),

Notice that the routines are named with the prefix FV_ instead of RE_ now. This is simply a visual cue that these are slightly modified versions. We've made a wrapper for each Regexp::Common routine so that it can be used as a named constraint like this.

Be sure to check out the Regexp::Common syntax for how its syntax works. It will make more sense to add future regular expressions to Regexp::Common rather than to Data::FormValidator.


You may also call these functions directly through the procedural interface by either importing them directly or importing the whole :validators group. This is useful if you want to use the built-in validators out of the usual profile specification interface.

For example, if you want to access the email validator directly, you could either do:

    use Data::FormValidator::Constraints (qw/valid_email/);
    use Data::FormValidator::Constraints (:validators);

    if (valid_email($email)) {
      # do something with the email address

Notice that when you call validators directly, you'll need to prefix the validator name with valid_

Each validator also has a version that returns the untainted value if the validation succeeded. You may call these functions directly through the procedural interface by either importing them directly or importing the :matchers group. For example if you want to untaint a value with the email validator directly you may:

    if ($email = match_email($email)) {
        system("echo $email");
    else {
        die "Unable to validate email";

Notice that when you call validators directly and want them to return an untainted value, you'll need to prefix the validator name with match_


New School Constraints Overview

This is the current recommended way to write constraints. See also Old School Constraints.

The most flexible way to create constraints to use closures a normal seeming outer subroutine which returins a customized DFV method subroutine as a result. It's easy to do. These constraint methods can be named whatever you like, and imported normally into the name space where the profile is located.

Let's look at an example.

  # Near your profile   
  # Of course, you don't have to export/import if your constraints are in the same
  # package as the profile.  
  use My::Constraints qw(coolness);

  # In your profile
  constraint_methods => {
    email                        => email(),
        prospective_date => coolness(
                min => 40,
                max => 60,
                {fields => [qw/personality smarts good_looks/]}

Let's look at how this complex CWcoolness constraint method works. The interface asks for users to define minimum and maximum coolness values, as well as declaring three data field names that we should peek into to look their values.

Here's what the code might look like:

  sub coolness {
        my ($min_cool,$max_cool, $attrs) = @_; 
        my ($personality,$smarts,$looks) = @{ $attrs->{fields} } if $attrs->{fields};
        return sub {
                my $dfv = shift;

                # Name it to refer to in the 'msgs' system.

                my $val = $dfv->get_current_constraint_value();

                # get other data to refer to
            my $data = $dfv->get_input_data;

            my $has_all_three = ($data->{personality} && $data->{smarts} && $data->{looks});
                return ( ($val >= $min_cool) && ($val <= $max_cool) && $has_all_three );

Here is documentation on how old school constraints are created. These are supported, but the the new school style documented above is recommended.

See also the CWvalidator_packages option in the input profile, for loading sets of old school constraints from other packages.

Old school constraint routines are named two ways. Some are named with the prefix CWmatch_ while others start with CWvalid_. The difference is that the CWmatch_ routines are built to untaint the data and return a safe version of it if it validates, while CWvalid_ routines simply return a true value if the validation succeeds and false otherwise.

It is preferable to write CWmatch_ routines that untaint data for the extra security benefits. Plus, Data::FormValidator will AUTOLOAD a CWvalid_ version if anyone tries to use it, so you only need to write one routine to cover both cases.

Usually constraint routines only need one input, the value being specified. However, sometimes more than one value is needed.


                image_field  => {  
                        constraint_method  => 'max_image_dimensions',
                        params => [\100,\200],

Using that syntax, the first parameter that will be passed to the routine is the Data::FormValidator object. The remaining parameters will come from the CWparams array. Strings will be replaced by the values of fields with the same names, and references will be passed directly.

In addition to CWconstraint_method, there is also an even older technique using the name CWconstraint instead. Routines that are designed to work with CWconstraint don't have access to Data::FormValidator object, which means users need to pass in the name of the field being validated. Besides adding unnecessary syntax to the user interface, it won't work in conjunction with CWconstraint_regexp_map.

Methods available for use inside of constraints

A few useful methods to use on the Data::FormValidator::Results object are available to you to use inside of your routine.

Returns the raw input data. This may be a CGI object if that's what was used in the constraint routine. Examples:
 # Raw and uncensored
 my $data = $self->get_input_data;
 # tamed to be a hashref, if it wasn't already
 my $data = $self->get_input_data( as_hashref => 1 );
Returns the name of the current field being tested in the constraint. Example:
 my $field = $self->get_current_constraint_field;
This reduces the number of parameters that need to be passed into the routine and allows multi-valued constraints to be used with CWconstraint_regexp_map. For complete examples of multi-valued constraints, see Data::FormValidator::Constraints::Upload
Returns the name of the current value being tested in the constraint. Example:
 my $value = $self->get_current_constraint_value;
This reduces the number of parameters that need to be passed into the routine and allows multi-valued constraints to be used with CWconstraint_regexp_map.
Returns the name of the current constraint being applied Example:
 my $value = $self->get_current_constraint_name;
This is useful for building a constraint on the fly based on it's name. It's used internally as part of the interface to the Regexp::Commmon regular expressions.
name_this =item set_current_constraint_name
Sets the name of the current constraint being applied. Example:
 sub my_constraint {
        my @outer_params = @_;
        return sub {
                my $dfv = shift;
                my @params = @outer_params;
                # do something constraining here...
By returning a closure which uses this method, you can build an advanced named constraint in your profile, before you actually have access to the DFV object that will be used later. See Data::FormValidator::Constraints::Upload for an example. CWname_this is a provided as a shorter synonym.

The CWmeta() method may also be useful to communicate meta data that may have been found. See Data::FormValidator::Results for documentation of that method.


Prior to Data::FormValidator 4.00, contraints were specified a bit differently. This older style is still supported.

It was not necessary to explicitly load some constraints into your name space, and the names were given as strings, like this:

    constraints  => {
            email             => 'email',
            fax               => 'american_phone',
            phone             => 'american_phone',
            state             => 'state',
                my_ip_address => 'RE_net_IPv4',
                other_ip => {
                        constraint => 'RE_net_IPv4',
                        params => [ \'-sep'=> \' ' ],
                my_cc_no      => {
                        constraint => 'cc_number',
                        params => [qw/cc_no cc_type/],


Data::FormValidator::Constraints::Upload - validate the bytes, format and dimensions of file uploads, Data::FormValidator::Constraints::DateTime - A newer DateTime constraint module. May save you a step of tranforming the date into a more useful format after it's validated. Data::FormValidator::Constraints::Dates - the original DFV date constraint module Regexp::Common lost of useful regular expressions to choose from!

Data::FormValidator Data::FormValidator::Filters Data::FormValidator::ConstraintsFactory


Some of those input validation functions have been taken from MiniVend by Michael J. Heins

The credit card checksum validation was taken from contribution by Bruce Albrecht to the MiniVend program.


    Francis J. Lacoste 
    Michael J. Heins 
    Bruce Albrecht  
    Mark Stosberg


Copyright (c) 1999 iNsu Innovations Inc. All rights reserved.

Parts Copyright 1996-1999 by Michael J. Heins Parts Copyright 1996-1999 by Bruce Albrecht Parts Copyright 2005 by Mark Stosberg

This program is free software; you can redistribute it and/or modify it under the terms as perl itself.