Data::FormValidator - Validates user input (usually from an HTML form) based on input profile.
| Use Case | Command | Description |
|---|---|---|
| Basic validation | my $results = Data::FormValidator->check(\%input, \%profile) | Validate input against a profile, returns a Results object |
| Define a profile | my $profile = { required => [...], optional => [...], constraint_methods => {...} } | Specify required/optional fields and constraints |
| Check for errors | if ($results->has_invalid or $results->has_missing) { ... } | Detect invalid or missing fields |
| Get valid data | my $valid = $results->valid | Retrieve hash of valid, filtered input |
| Use built-in constraint | email => email() | Apply a named constraint (e.g. email, zip, etc.) |
| Apply filters | filters => ['trim'] | Trim whitespace from all fields before validation |
| Require some fields | require_some => { group => [2, qw/field1 field2/] } | Require at least N fields from a group |
| Dependent fields | dependencies => { cc_no => [qw/cc_type cc_exp/] } | Make fields required when another field is present |
| Multiple constraints | field => [ 'constraint1', { constraint_method => ..., name => 'name' } ] | Apply multiple constraints to one field |
| Custom error messages | msgs => { invalid => 'Problematic!', constraints => { 'name' => 'msg' } } | Override default error messages |
use Data::FormValidator;
my $results = Data::FormValidator->check(\%input_hash, \%dfv_profile);
if ($results->has_invalid or $results->has_missing) {
# do something with $results->invalid, $results->missing
# or $results->msgs
}
else {
# do something with $results->valid
}
Data::FormValidator's main aim is to make input validation expressible in a simple format.
Data::FormValidator lets you define profiles which declare the required and optional fields and any constraints they might have.
The results are provided as an object, which makes it easy to handle missing and invalid results, return error messages about which constraints failed, or process the resulting valid data.
my $results = Data::FormValidator->check(\%input_hash, \%dfv_profile);
"check" is the recommended method to use to validate forms. It returns its results as a Data::FormValidator::Results object. A deprecated method "validate" described below is also available, returning its results as an array.
use Data::FormValidator;
my $results = Data::FormValidator->check(\%input_hash, \%dfv_profile);
Here, "check()" is used as a class method, and takes two required parameters.
The first a reference to the data to be validated. This can either be a hash reference, or a CGI.pm-like object. In particular, the object must have a param() method that works like the one in CGI.pm does. CGI::Simple and Apache::Request objects are known to work in particular. Note that if you use a hash reference, multiple values for a single key should be presented as an array reference.
The second argument is a reference to the profile you are validating.
my( $valids, $missings, $invalids, $unknowns ) =
Data::FormValidator->validate( \%input_hash, \%dfv_profile);
"validate()" provides a deprecated alternative to "check()". It has the same input syntax, but returns a four element array:
Using "new()" is only needed for advanced usage:
my $dfv = Data::FormValidator->new({
profile_1 => { # usual profile definition here },
profile_2 => { # another profile definition },
});
You can also load profiles from a file:
my $dfv = Data::FormValidator->new('/path/to/profiles.pl');
Now call check() with the profile name:
my $results = $dfv->check(\%input_hash,'profile_1');
my $dfv = Data::FormValidator->new({}, {
# your defaults here
});
Subsequent calls to check() on this object will use those defaults. Any definition of a key in your validation profile will completely overwrite your default value, except for the "msgs" key which merges safely.
An input profile is a hash reference containing one or more of the following keys. Here is a very simple input profile:
use Data::FormValidator::Constraints qw(:closures);
my $profile = {
optional => [qw( company
fax
country )],
required => [qw( fullname
phone
email
address )],
constraint_methods => {
email => email(),
}
};
Array reference of field names that are required. Missing or whitespace-only fields are reported as missing.
required_regexp => qr/city|state|zipcode/,
Regular expression to specify additional field names that will be required.
require_some => {
# require any two fields from this group
city_or_state_or_zipcode => [ 2, qw/city state zipcode/ ],
}
Hash reference defining groups where 1 or more fields from the group should be required. Keys are group names. Values are array references: first element is the number of fields required (defaults to 1 if not a digit), rest are field names.
optional => [qw/meat coffee chocolate/],
Array reference of optional field names. If present, they will be checked for validity. Fields not in optional or required lists are reported as unknown.
optional_regexp => qr/_province$/,
Regular expression to specify additional optional fields.
dependencies => {
# If cc_no is entered, make cc_type and cc_exp required
"cc_no" => [ qw( cc_type cc_exp ) ],
# if pay_type eq 'check', require check_no
"pay_type" => {
check => [ qw( check_no ) ],
}
# if cc_type is VISA or MASTERCARD require CVV
"cc_type" => sub {
my $dfv = shift;
my $type = shift;
return [ 'cc_cvv' ] if ($type eq "VISA" || $type eq "MASTERCARD");
return [ ];
},
},
For optional fields that have other requirements. Array reference: those fields become required when the target field is present. Hash reference: the target field must equal a key. Code reference: returns the dependent fields.
dependency_groups => {
# if either field is filled in, they all become required
password_group => [qw/password password_confirmation/],
}
Hash reference where values are arrays of field names. If any field in the group is filled, all become required.
dependencies_regexp => {
qr/Line\d+\_ItemType$/ => sub {
my $dfv = shift;
my $itemtype = shift;
my $field = shift;
if ($type eq 'NeedsBatteries') {
my ($prefix, $suffix) = split(/\_/, $field);
return([$prefix . '_add_batteries]);
} else {
return([]);
}
},
},
Regular expression to specify additional dependent fields.
dependent_optionals => {
# If delivery_address is specified then delivery_notes becomes optional
"delivery_address" => [ qw( delivery_notes ) ],
# if delivery_type eq 'collection', collection_notes becomes optional
"delivery_type" => {
collection => [ qw( collection_notes ) ],
}
# if callback_type is "phone" or "email" then additional_notes becomes optional
"callback_type" => sub {
my $dfv = shift;
my $type = shift;
if ($type eq 'phone' || $type eq 'email') {
return(['additional_notes']);
} else {
return([]);
}
},
},
For optional fields that can trigger other optional fields. Works like dependencies but for optional fields.
dependent_require_some => {
# require any fields from this group if AddressID is "new"
AddressID => sub {
my $dfv = shift;
my $value = shift;
if ($value eq 'new') {
return({
house_name_or_number => [ 1, 'HouseName', 'HouseNumber' ],
});
} else {
return;
}
},
}
Allows a field to trigger require_some groups. Returns a hashref similar to require_some.
defaults => {
country => "USA",
},
Hash reference of field names to default values. Values can be code refs that receive the Results object.
defaults_regexp_map => {
qr/^opt_/ => 1,
},
Map regular expressions to default values for matching optional or required fields. Useful for checkbox fields.
filters => ['trim'],
Array reference of filters applied to ALL optional and required fields before constraints. Can be built-in (trim, digit, etc.) or anonymous subroutines. See Data::FormValidator::Filters.
field_filters => {
cc_no => ['digit'],
},
Hash ref with field names as keys, values are array references of filters.
field_filter_regexp_map => {
# Upper-case the first letter of all fields that end in "_name"
qr/_name$/ => ['ucfirst'],
},
Apply filters to fields matching a regular expression.
use Data::FormValidator::Constraints qw(:closures);
constraint_methods => {
cc_no => cc_number({fields => ['cc_type']}),
cc_type => cc_type(),
cc_exp => cc_exp(),
},
Hash ref of constraints for field validation. Values can be:
zip()qr/^\d{5}$/sub { my $val = pop; return $val =~ '/^\d{5}$/' }use Data::FormValidator::Constraints qw(:closures);
constraint_method_regexp_map => {
# All fields that end in _postcode have the 'postcode' constraint applied.
qr/_postcode$/ => postcode(),
},
Add constraints to fields matching a regular expression.
untaint_all_constraints => 1,
If set, all form data that passes a constraint will be untainted. Overridden by untaint_constraint_fields and untaint_regexp_map.
untaint_constraint_fields => [qw(zipcode state)],
Specifies fields to untaint if they pass constraints.
untaint_regexp_map => [qr/some_field_\d/],
Specifies fields matching a regex to untaint if they pass constraints.
missing_optional_valid => 1
When true, optional fields with empty values are included in the valid hash. Important for update forms.
validator_packages => [qw(Data::FormValidator::Constraints::Upload)],
Load constraint and filter routines from other packages. Routines starting with match_, valid_, and filter_ are imported.
Defines error message formatting. Default: <span style="color:red;font-weight:bold" class="dfv_errors">* %s</span>
msgs => {
# set a custom error prefix, defaults to none
prefix=> 'error_',
# Set your own "Missing" message, defaults to "Missing"
missing => 'Not Here!',
# Default invalid message, default's to "Invalid"
invalid => 'Problematic!',
# message separator for multiple messages
# Defaults to ' '
invalid_separator => ' <br /> ',
# formatting string, default given above.
format => 'ERROR: %s',
# Error messages, keyed by constraint name
constraints => {
'date_and_time' => 'Not a valid time format',
# ...
},
# This token will be included in the hash if there are
# any errors returned. This can be useful with templating
# systems like HTML::Template
# The 'prefix' setting does not apply here.
# defaults to undefined
any_errors => 'some_errors',
}
Experimental: provide a code reference to generate custom messages:
msgs => \&my_msgs_callback
Called as a Data::FormValidator::Results method.
debug => 1
Prints details to STDERR (currently only level 1).
Wherever an array reference is expected, you can use a string for a single value. Example:
filters => 'trim'
Preferred: qr/.../. Deprecated but supported: 'm/.../'
You can pass more than one value into a constraint routine. The value of the constraint should be a hash reference with keys constraint (subroutine name or reference) and params (array reference of other fields to pass). Example:
cc_no => {
constraint => "cc_number",
params => [ qw( cc_no cc_type ) ],
},
Use an array reference to apply multiple constraints to a single field. Each element can be any constraint type. Name constraints for failure identification:
my_zipcode_field => [
'zip',
{
constraint_method => '/^406/',
name => 'starts_with_406',
}
],
For more advanced validation, see other modules in this distribution. Profiles can also be built dynamically.
my( $valids, $missings, $invalids, $unknowns ) =
Data::FormValidator->validate( \%input_hash, \%dfv_profile);
Deprecated alternative to check(). Returns a four-element array:
Deprecated. Use constraint_methods instead.
constraints => {
cc_no => {
constraint => "cc_number",
params => [ qw( cc_no cc_type ) ],
},
cc_type => "cc_type",
cc_exp => "cc_exp",
},
Older technique. Use constraint_methods and $self->name_this('foo')> instead.
# supply multiple parameters
cc_no => {
constraint => "cc_number",
params => [ qw( cc_no cc_type ) ],
},
# name a constraint, useful for returning error messages
last_name => {
name => "ends_in_name",
constraint => qr/_name$/,
},
Deprecated. Use constraint_methods_regexp_map instead.
constraint_regexp_map => {
qr/_postcode$/ => 'postcode',
},
Some input validation functions from MiniVend by Michael J. Heins. Credit card checksum validation from Bruce Albrecht.
Report bugs at RT. Patches welcome.
Maintained on Github: https://github.com/dnmfarrell/Data-FormValidator
Currently maintained by David Farrell <dfarrell AT cpan.org>. Parts Copyright 2001-2006 by Mark Stosberg. Copyright (c) 1999 Francis J. Lacoste and iNsu Innovations Inc. Parts Copyright 1996-1999 by Michael J. Heins and Bruce Albrecht.
This program is free software; you can redistribute it and/or modify it under the terms as perl itself.
Generated by phpman v4.9.26-5-g7740029 Author: Che Dong Under GNU General Public License
2026-08-14 21:46 @2600:1f28:365:80b0:4d23:66fa:c2bb:7bae
CrawledBy CCBot/2.0 (https://commoncrawl.org/faq/)