info > Data::FormValidator::Constraints

๐Ÿ“Œ NAME

Data::FormValidator::Constraints โ€” Basic sets of constraints on input profile.

๐Ÿš€ Quick Reference

Use CaseCommandDescription
Validate email addressemail()Checks if input looks like an email address (RFCโ€‘ish).
Validate N. American phoneamerican_phone()Checks (XXX) XXXโ€‘XXXX format, 7+ digits.
Check character length (min/max)FV_length_between(1,23)Inclusive length check in Perl characters.
Check max lengthFV_max_length(100)Inclusive โ€“ allows length 100.
Check min lengthFV_min_length(1)Inclusive โ€“ allows length 1.
Compare two fieldsFV_eq_with('field')Ensures current field equals another field.
Check number of valuesFV_num_values(1)Ensures exactly one value for a parameter.
Check number of values rangeFV_num_values_between(1,4)Inclusive bounds on array size.
Validate U.S. statestate()Twoโ€‘letter abbreviation check.
Validate Canadian provinceprovince()Twoโ€‘letter abbreviation check.
Validate U.S. zip codezip()5 digits + optional mailbox number.
Validate Canadian postal codepostcode()Canadian postal code format.
Validate phone (generic)phone()At least 6 digits.
Validate credit card numbercc_number({fields=>['cc_type']})Checksum and digit pattern (catches typos).
Validate credit card expirationcc_exp()MM/YY or MM/YYYY, not in past.
Validate credit card typecc_type()Starts with M, V, A, or D.
Validate IP address (v4)ip_addressDotted decimal format.
Use Regexp::Common patternsFV_net_IPv4()Wraps any RE_ pattern as a named constraint.

๐Ÿ“– SYNOPSIS

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',
       },
    },

๐Ÿ“ DESCRIPTION

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.

๐Ÿ“ FV_length_between(1,23)

๐Ÿ“ FV_max_length(23)

๐Ÿ“ FV_min_length(1)

use Data::FormValidator::Constraints qw(
  FV_length_between
  FV_min_length
  FV_max_length
);

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.

๐Ÿ”— FV_eq_with

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.

๐Ÿ”ข FV_num_values

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.

๐Ÿ”ข FV_num_values_between

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.

๐Ÿ“ง email

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.

๐Ÿ™๏ธ state_or_province

This one checks if the input correspond to an american state or a canadian province.

๐Ÿ state

This one checks if the input is a valid two letter abbreviation of an American state.

๐Ÿ”๏ธ province

This checks if the input is a two letter Canadian province abbreviation.

๐Ÿ“ฎ zip_or_postcode

This constraints checks if the input is an American zipcode or a Canadian postal code.

๐Ÿ“ฎ postcode

This constraints checks if the input is a valid Canadian postal code.

๐Ÿ“ฎ zip

This input validator checks if the input is a valid american zipcode : 5 digits followed by an optional mailbox number.

๐Ÿ“ž phone

This one checks if the input looks like a phone number, (if it contains at least 6 digits.)

๐Ÿ“ž american_phone

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.

๐Ÿ’ณ cc_number

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.

๐Ÿ“… cc_exp

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.

๐Ÿ’ณ cc_type

This one checks if the input field starts by M(asterCard), V(isa), A(merican express) or D(iscovery).

๐ŸŒ ip_address

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.

โœ๏ธ RENAMING BUILT-IN CONSTAINTS

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',
    }
},

๐Ÿ”Œ REGEXP::COMMON SUPPORT

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.

โš™๏ธ PROCEDURAL INTERFACE

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/);
or
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_"

๐Ÿ› ๏ธ WRITING YOUR OWN CONSTRAINT ROUTINES

๐Ÿง‘โ€๐Ÿ’ป 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.
      $dfv->name_this('coolness');

      # 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  {
    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.

get_input_data()

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

get_filtered_data()

my $data = $self->get_filtered_data;

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

get_current_constraint_field()

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

For complete examples of multi-valued constraints, see Data::FormValidator::Constraints::Upload

get_current_constraint_value()

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

get_current_constraint_name()

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 its name. It's used internally as part of the interface to the Regexp::Commmon regular expressions.

untainted_constraint_value()

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.

name_this() / 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;
       $dfv->set_current_constraint_name('my_constraint');
       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.

๐Ÿ”„ BACKWARDS COMPATIBILITY

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/],
    }
},

๐Ÿ‘€ SEE ALSO

Constraints available in other modules

Related modules in this package

๐Ÿ† CREDITS

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.

โœ๏ธ AUTHORS

ยฉ๏ธ COPYRIGHT

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.

Data::FormValidator::Constraints
๐Ÿ“Œ NAME ๐Ÿš€ Quick Reference ๐Ÿ“– SYNOPSIS ๐Ÿ“ DESCRIPTION
๐Ÿ“ FV_length_between(1,23) ๐Ÿ“ FV_max_length(23) ๐Ÿ“ FV_min_length(1) ๐Ÿ”— FV_eq_with ๐Ÿ”ข FV_num_values ๐Ÿ”ข FV_num_values_between ๐Ÿ“ง email ๐Ÿ™๏ธ state_or_province ๐Ÿ state ๐Ÿ”๏ธ province ๐Ÿ“ฎ zip_or_postcode ๐Ÿ“ฎ postcode ๐Ÿ“ฎ zip ๐Ÿ“ž phone ๐Ÿ“ž american_phone ๐Ÿ’ณ cc_number ๐Ÿ“… cc_exp ๐Ÿ’ณ cc_type ๐ŸŒ ip_address
โœ๏ธ RENAMING BUILT-IN CONSTAINTS ๐Ÿ”Œ REGEXP::COMMON SUPPORT โš™๏ธ PROCEDURAL INTERFACE ๐Ÿ› ๏ธ WRITING YOUR OWN CONSTRAINT ROUTINES
๐Ÿง‘โ€๐Ÿ’ป New School Constraints Overview ๐Ÿ”ง Methods available for use inside of constraints
๐Ÿ”„ BACKWARDS COMPATIBILITY ๐Ÿ‘€ SEE ALSO
Constraints available in other modules Related modules in this package
๐Ÿ† CREDITS โœ๏ธ AUTHORS ยฉ๏ธ COPYRIGHT

Generated by phpman v4.9.26-5-g7740029 Author: Che Dong Under GNU General Public License
2026-08-14 20:20 @2600:1f28:365:80b0:4d23:66fa:c2bb:7bae
CrawledBy CCBot/2.0 (https://commoncrawl.org/faq/)
Valid XHTML 1.0 Transitional!Valid CSS!