Data::FormValidator - Validates user input (usually from an HTML form) based on input profile.
| Use Case | Command | Description |
|---|---|---|
| Basic validation | Data::FormValidator->check(\%input, \%profile) | π’ Returns a Results object with has_invalid, has_missing, valid, invalid, missing |
| Define required fields | required => [qw/field1 field2/] | π΄ Missing fields reported |
| Define optional fields | optional => [qw/field1 field2/] | π‘ Only checked if submitted |
| Apply constraints | constraint_methods => { email => email() } | β Use built-in or custom constraints |
| Dependencies | dependencies => { "field" => [qw/dep1 dep2/] } | π If field present, dependents become required |
| Set defaults | defaults => { country => "USA" } | π₯ Missing fields get default values |
| Apply filters | filters => ['trim'] | π§Ή Pre-process all fields |
| Custom error messages | msgs => { invalid => 'Invalid!', constraints => { 'name' => 'msg' } } | π£οΈ Override default messages |
| Multiple constraints per field | field => [ \&constraint1, qr/regex/ ] | π’ Apply several checks |
| Untaint validated data | untaint_all_constraints => 1 | π Automatically untaint passed values |
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. It lets you define profiles which declare the required and optional fields and any constraints they might have. The results are provided as an object, making it easy to handle missing and invalid results, return error messages, or process the valid data.
check()my $results = Data::FormValidator->check(\%input_hash, \%dfv_profile);
"check" is the recommended method. It returns a Data::FormValidator::Results object. The first argument is a hash reference or a CGI-like object with a param() method. The second is a profile reference.
validate() (deprecated)my( $valids, $missings, $invalids, $unknowns ) =
Data::FormValidator->validate( \%input_hash, \%dfv_profile);
Returns a four-element array:
new()Advanced usage β loading multiple profiles, or applying defaults. Example:
my $dfv = Data::FormValidator->new({
profile_1 => { # usual profile definition here },
profile_2 => { # another profile definition },
});
Then call $dfv->check(\%input, 'profile_1').
An input profile is a hash reference containing one or more of the following keys:
requiredArray reference of field names that must be present. Missing fields are reported.
required_regexprequired_regexp => qr/city|state|zipcode/,
Regular expression to specify additional required fields.
require_somerequire_some => {
city_or_state_or_zipcode => [ 2, qw/city state zipcode/ ],
}
Hash of groups where at least n fields from the group must be filled.
optionaloptional => [qw/meat coffee chocolate/],
These fields MAY be present; if so, they are validated.
optional_regexpoptional_regexp => qr/_province$/,
Regex to mark additional optional fields.
dependenciesdependencies => {
"cc_no" => [ qw( cc_type cc_exp ) ],
"pay_type" => {
check => [ qw( check_no ) ],
},
"cc_type" => sub {
my $dfv = shift;
my $type = shift;
return [ 'cc_cvv' ] if ($type eq "VISA" || $type eq "MASTERCARD");
return [ ];
},
},
Makes fields required when a specific optional field is present. Can be array, hash (valueβdependent), or code ref.
dependency_groupsdependency_groups => {
password_group => [qw/password password_confirmation/],
}
If any field in the group is filled, all become required.
dependencies_regexpdependencies_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([]);
}
},
},
Regexβbased dependencies for dynamic field names.
dependent_optionalsdependent_optionals => {
"delivery_address" => [ qw( delivery_notes ) ],
"delivery_type" => {
collection => [ qw( collection_notes ) ],
},
"callback_type" => sub {
my $dfv = shift;
my $type = shift;
if ($type eq 'phone' || $type eq 'email') {
return(['additional_notes']);
} else {
return([]);
}
},
},
Makes optional fields conditionally required when another optional field is present.
dependent_require_somedependent_require_some => {
AddressID => sub {
my $dfv = shift;
my $value = shift;
if ($value eq 'new') {
return({
house_name_or_number => [ 1, 'HouseName', 'HouseNumber' ],
});
} else {
return;
}
},
}
Conditionally applies require_some logic based on another field's value.
defaultsdefaults => {
country => "USA",
},
Default values for missing fields. Values can be code refs.
defaults_regexp_mapdefaults_regexp_map => {
qr/^opt_/ => 1,
},
Set defaults for fields matching a regex (e.g., unchecked checkboxes).
filtersfilters => ['trim'],
Array of filters applied to ALL optional and required fields before constraints.
field_filtersfield_filters => {
cc_no => ['digit'],
},
Perβfield filters.
field_filter_regexp_mapfield_filter_regexp_map => {
qr/_name$/ => ['ucfirst'],
},
Apply filters to fields matching a regex.
constraint_methodsuse 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 field names to constraints. Values can be:
zip())qr/^\d{5}$/)constraint_method_regexp_mapconstraint_method_regexp_map => {
qr/_postcode$/ => postcode(),
},
Apply constraints to fields matching a regex.
untaint_all_constraintsuntaint_all_constraints => 1,
Untaint all data that passes constraints.
untaint_constraint_fieldsuntaint_constraint_fields => [qw(zipcode state)],
Untaint specific fields.
untaint_regexp_mapuntaint_regexp_map => [qr/some_field_\d/],
Untaint fields matching a regex.
missing_optional_validmissing_optional_valid => 1
Include optional fields with empty values in the valid hash.
validator_packagesvalidator_packages => [qw(Data::FormValidator::Constraints::Upload)],
Load additional constraint and filter packages.
msgsmsgs => {
prefix => 'error_',
missing => 'Not Here!',
invalid => 'Problematic!',
invalid_separator => ' <br /> ',
format => 'ERROR: %s',
constraints => {
'date_and_time' => 'Not a valid time format',
},
any_errors => 'some_errors',
}
Custom error message formatting. Also supports a callback: msgs => \&my_msgs_callback.
debugdebug => 1,
Prints debug info to STDERR.
Where an array ref is expected, you can use a single string: filters => 'trim' instead of filters => ['trim'].
Both qr// and deprecated string style ('m/.../') are supported.
To pass multiple values to a constraint, use a hash reference:
cc_no => {
constraint => "cc_number",
params => [ qw( cc_no cc_type ) ],
},
See Data::FormValidator::Constraints for the newer syntax.
Use an array reference to apply multiple constraints to a single field:
my_zipcode_field => [
'zip',
{
constraint_method => '/^406/',
name => 'starts_with_406',
}
],
Each can be a named constraint, regex, or subroutine. Use name to distinguish failures.
See other modules in the distribution. Profiles can be built dynamically with Perl code.
validate()Deprecated alternative to check(). Returns four array elements as described previously.
constraints (profile key)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 for naming constraints or supplying multiple parameters:
cc_no => {
constraint => "cc_number",
params => [ qw( cc_no cc_type ) ],
},
last_name => {
name => "ends_in_name",
constraint => qr/_name$/,
},
constraint_regexp_map (profile key)Deprecated β use constraint_methods_regexp_map.
constraint_regexp_map => {
qr/_postcode$/ => 'postcode',
},
Validating Web Forms with Perl, http://mark.stosberg.com/Tech/perl/form-validation/
Japanese: http://perldoc.jp/docs/modules/
FreeBSD: p5-Data-FormValidator, Debian: libdata-formvalidator-perl
Some input validation functions from MiniVend by Michael J. Heins. Credit card checksum validation from Bruce Albrecht.
Bug reports and patches welcome. Tests with Test::More are helpful. http://rt.cpan.org/NoAuth/Bugs.html?Dist=Data-FormValidator
Maintained on Github: https://github.com/dnmfarrell/Data-FormValidator
Currently maintained by David Farrell <dfarrell AT cpan.org>. Parts Copyright 2001β2006 Mark Stosberg. Copyright 1999 Francis J. Lacoste and iNsu Innovations Inc. Parts Copyright 1996β1999 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.10.0-16-g1a0e228 · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-09-22 22:55 @216.73.217.0
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)