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


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

In an Data::FormValidator profile:

    constraint_methods => {
        email   => email(),
        phone   => american_phone(),
        first_names =>  {
           constraint_method => FV_max_length(3),
           name => 'my_custom_name',
    msgs => {
       constraints => {
            my_custom_name => 'My message',


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.




  use Data::FormValidator::Constraints qw(
  constraint_methods => {
    # specify a min and max, inclusive
    last_name        => FV_length_between(1,23),

Specify a length constraint for a field.

These constraints have a different naming convention because they are higher-order functions. They take input and return a code reference to a standard constraint method. A constraint name of "length_between", "min_length", or "max_length" will be set, corresponding to the function name you choose.

The checks are all inclusive, so a max length of '100' will allow the length 100.

Length is measured in perl characters as opposed to bytes or anything else.

This constraint will untaint your data if you have untainting turned on. However, a length check alone may not be enough to insure the safety of the data you are receiving. Using additional constraints to check the data is encouraged.


  use Data::FormValidator::Constraints qw( FV_eq_with );
  constraint_methods => {
    password  => FV_eq_with('password_confirm'),

Compares the current field to another field. A constraint name of "eq_with" will be set.


    use Data::FormValidator::Constraints qw ( FV_num_values );
    constraint_methods => {
        attachments => FV_num_values(4),

Checks the number of values in the array named by this param. Note that this is useful for making sure that only one value was passed for a given param (by supplying a size argument of 1). A constraint name of "num_values" will be set.


    use Data::FormValidator::Constraints qw ( FV_num_values_between );
    constraint_methods => {
        attachments => FV_num_values_between(1,4),

Checks that the number of values in the array named by this param is between the supplied bounds (inclusively). A constraint name of "num_values_between" will be set.


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 a dotted decimal IP address (v4). For other kinds of IP address method, See Regexp::Common::net which provides several more options. ``REGEXP::COMMON SUPPORT'' explains how we easily integrate with Regexp::Common.


If you'd like, you can rename any of the built-in constraints. Just define the constraint_method and name in a hashref, like this:

        constraint_methods => {
            first_names =>  {
                constraint_method => FV_max_length(3),
                name => 'custom_length',


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 returns 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 'coolness';
  # In your profile
  constraint_methods => {
    email            => email(),
    prospective_date => coolness( 40, 60,
        {fields => [qw/personality smarts good_looks/]}

Let's look at how this complex "coolness" 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.
        # value of 'prospective_date' parameter
        my $val = $dfv->get_current_constraint_value();
        # get other data to refer to
        my $data = $dfv->get_filtered_data;
        my $has_all_three = ($data->{$personality} && $data->{$smarts} && $data->{$looks});
        return ( ($val >= $min_cool) && ($val <= $max_cool) && $has_all_three );

Old School Constraints

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

See also the "validator_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 "match_" while others start with "valid_". The difference is that the "match_" routines are built to untaint the data and return a safe version of it if it validates, while "valid_" routines simply return a true value if the validation succeeds and false otherwise.

It is preferable to write "match_" routines that untaint data for the extra security benefits. Plus, Data::FormValidator will AUTOLOAD a "valid_" 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 "params" array. Strings will be replaced by the values of fields with the same names, and references will be passed directly.

In addition to "constraint_method", there is also an even older technique using the name "constraint" instead. Routines that are designed to work with "constraint" 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 "constraint_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.


 # 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 );


 my $data = $self->get_filtered_data;

Returns the valid filtered data as a hashref, regardless of whether it started out as a compatible object. Multiple values are expressed as array references.


Returns the name of the current field being tested in the constraint.


 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 "constraint_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.


 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 "constraint_regexp_map".


Returns the name of the current constraint being applied


 my $value = $self->get_current_constraint_name;

This is useful for building a constraint on the fly based on its name. It's used internally as part of the interface to the Regexp::Commmon regular expressions.


   return $dfv->untainted_constraint_value($match);

If you have written a constraint which untaints, use this method to return the untainted result. It will prepare the right result whether the user has requested untainting or not.



Sets the name of the current constraint being applied.


 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.

"name_this" is a provided as a shorter synonym.

The "meta()" 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, constraints 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/],

Constraints available in other modules

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 transforming the date into a more useful format after it's validated.
Data::FormValidator::Constraints::Dates - the original DFV date constraint module. Try the newer one first!
Data::FormValidator::Constraints::Japanese - Japan-specific constraints
Data::FormValidator::Constraints::MethodsFactory - a useful collection of tools generate more complex constraints. Recommended!

Related modules in this package

Data::FormValidator::Filters - transform data before constraints are applied
Data::FormValidator::ConstraintsFactory - This is a historical collection of constraints that suffer from cumbersome names. They are worth reviewing though--- "make_and_constraint" will allow one to validate against a list of constraints and shortcircuit if the first one fails. That's perfect if the second constraint depends on the first one having passed. For a modern version of this toolkit, see Data::FormValidator::Constraints::MethodsFactory.


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-2009 by Mark Stosberg

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