blib/lib/Data/FormValidator.pm

filter: Statementstmt 100% 118 / 118 Branchbran 90.3% 47 / 52 Conditioncond 63.6% 7 / 11 MC/DCmcdc 42.8% 3 / 7 Subroutinesub 92.8% 13 / 14 Podpod 75.0% 3 / 4 totaltotal 92.7% 191 / 206 CC 37 SCAR 23.8
CC
37
Cov
95%
_check_profile_syntax
20.0
load_profiles
7.3
check
7.0
CRAP 10.8
« blib/lib/Data/FormValidator/Constraints/Upload.pm ↑ Summary blib/lib/Data/FormValidator/Constraints.pm »
1  
2 # FormValidator.pm - Object that validates form input data.
3 #
4 # This file is part of Data::FormValidator.
5 #
6 # Author: Francis J. Lacoste
7 # Previous Maintainer: Mark Stosberg <mark@stosberg.com>
8 # Maintainer: David Farrell <dfarrell@cpan.org>
9 #
10 # Copyright (C) 1999 Francis J. Lacoste, iNsu Innovations
11 # Parts Copyright 1996-1999 by Michael J. Heins
12 # Parts Copyright 1996-1999 by Bruce Albrecht
13 # Parts Copyright 2001-2005 by Mark Stosberg
14 #
15 # Parts of this module are based on work by
16 # Bruce Albrecht, contributed to
17 # MiniVend.
18 #
19 # Parts also based on work by Michael J. Heins
20 #
21 # This program is free software; you can redistribute it and/or modify
22 # it under the terms same terms as perl itself.
23  
24  
25 package Data::FormValidator;
26 59 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
27 59 ▶use File::Spec qw();
Subroutine BEGIN: called CC=1 SCAR=0.0
28 59 ▶use 5.008;
Subroutine BEGIN: called CC=1 SCAR=0.0
29  
30 59 ▶use Data::FormValidator::Results;
Subroutine BEGIN: called CC=1 SCAR=0.0
31 59 *_arrayify = \&Data::FormValidator::Results::_arrayify;
32 59 ▶use Data::FormValidator::Filters ':filters';
Subroutine BEGIN: called CC=1 SCAR=0.0
33 59 ▶use Data::FormValidator::Constraints qw(:validators :matchers);
Subroutine BEGIN: called CC=1 SCAR=0.0
34  
35 59 our $VERSION = 4.88;
36  
37 59 our %EXPORT_TAGS = (
38 filters => [qw/
39 filter_alphanum
40 filter_decimal
41 filter_digit
42 filter_dollars
43 filter_integer
44 filter_lc
45 filter_neg_decimal
46 filter_neg_integer
47 filter_phone
48 filter_pos_decimal
49 filter_pos_integer
50 filter_quotemeta
51 filter_sql_wildcard
52 filter_strip
53 filter_trim
54 filter_uc
55 filter_ucfirst
56 /],
57 validators => [qw/
58 valid_american_phone
59 valid_cc_exp
60 valid_cc_number
61 valid_cc_type
62 valid_email
63 valid_ip_address
64 valid_phone
65 valid_postcode
66 valid_province
67 valid_state
68 valid_state_or_province
69 valid_zip
70 valid_zip_or_postcode
71 /],
72 matchers => [qw/
73 match_american_phone
74 match_cc_exp
75 match_cc_number
76 match_cc_type
77 match_email
78 match_ip_address
79 match_phone
80 match_postcode
81 match_province
82 match_state
83 match_state_or_province
84 match_zip
85 match_zip_or_postcode
86 /],
87 );
88 59 our @EXPORT_OK = (@{ $EXPORT_TAGS{filters} }, @{ $EXPORT_TAGS{validators} }, @{ $EXPORT_TAGS{matchers} });
89  
90  
91 59 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
92 59 ▶use Symbol;
Subroutine BEGIN: called CC=1 SCAR=0.0
93  
94  
95 0 ▶sub DESTROY {}
Subroutine DESTROY: not called CC=1 SCAR=0.0
96  
97 =pod
98  
99 =head1 NAME
100  
101 Data::FormValidator - Validates user input (usually from an HTML form) based
102 on input profile.
103  
104 =head1 SYNOPSIS
105  
106 use Data::FormValidator;
107  
108 my $results = Data::FormValidator->check(\%input_hash, \%dfv_profile);
109  
110 if ($results->has_invalid or $results->has_missing) {
111 # do something with $results->invalid, $results->missing
112 # or $results->msgs
113 }
114 else {
115 # do something with $results->valid
116 }
117  
118  
119 =head1 DESCRIPTION
120  
121 Data::FormValidator's main aim is to make input validation expressible in a
122 simple format.
123  
124 Data::FormValidator lets you define profiles which declare the
125 required and optional fields and any constraints they might have.
126  
127 The results are provided as an object, which makes it easy to handle
128 missing and invalid results, return error messages about which constraints
129 failed, or process the resulting valid data.
130  
131 =cut
132  
133 32 ▶sub new {
Subroutine new: called CC=5 SCAR=16.1
Pod documented
134 32 my $proto = shift;
135 32 my $profiles_or_file = shift;
136 32 my $defaults = shift;
137  
138 32 ▶ my $class = ref $proto || $proto;
Condition33%1/3
ref $proto || $proto
l!l&&r!l&&!r
0320
MC/DC0%0/2
ref $proto || $proto
ref $proto $proto
Truth table33%1/3
A || B
A= ref $protoB= $proto
ABresult
1X1
011
000
139  
140 32 ▶ if ($defaults) {
Branch: 1 branch
BranchTrueFalseTotal
if ($defaults) 4 28 32
141 4 ▶ ref $defaults eq 'HASH' or
Branch: 1 branch
BranchTrueFalseTotal
ref $defaults eq "HASH" or die "second argument to new must be a hash ref" 3 1 4
142 die 'second argument to new must be a hash ref';
143 }
144  
145 31 my ($file, $profiles);
146  
147 31 ▶ if (ref $profiles_or_file) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $profiles_or_file) { } 28 3 31
148 28 $profiles = $profiles_or_file;
149 }
150 else {
151 3 $file = File::Spec->rel2abs( $profiles_or_file );
152 }
153  
154  
155 31 bless {
156 profile_file => $file,
157 profiles => $profiles,
158 defaults => $defaults,
159 }, $class;
160 }
161  
162 =head1 VALIDATING INPUT
163  
164 =head2 check()
165  
166 my $results = Data::FormValidator->check(\%input_hash, \%dfv_profile);
167  
168 C<check> is the recommended method to use to validate forms. It returns its results as a
169 L<Data::FormValidator::Results|Data::FormValidator::Results> object. A
170 deprecated method C<validate> described below is also available, returning its results as an
171 array.
172  
173 use Data::FormValidator;
174 my $results = Data::FormValidator->check(\%input_hash, \%dfv_profile);
175  
176 Here, C<check()> is used as a class method, and takes two required parameters.
177  
178 The first a reference to the data to be be validated. This can either be a hash
179 reference, or a CGI.pm-like object. In particular, the object must have a param()
180 method that works like the one in CGI.pm does. CGI::Simple and Apache::Request
181 objects are known to work in particular. Note that if you use a hash reference,
182 multiple values for a single key should be presented as an array reference.
183  
184 The second argument is a reference to the profile you are validating.
185  
186 =head2 validate()
187  
188 my( $valids, $missings, $invalids, $unknowns ) =
189 Data::FormValidator->validate( \%input_hash, \%dfv_profile);
190  
191 C<validate()> provides a deprecated alternative to C<check()>. It has the same input
192 syntax, but returns a four element array, described as follows
193  
194 =over
195  
196 =item valids
197  
198 This is a hash reference to the valid fields which were submitted in
199 the data. The data may have been modified by the various filters specified.
200  
201 =item missings
202  
203 This is a reference to an array which contains the name of the missing
204 fields. Those are the fields that the user forget to fill or filled
205 with spaces. These fields may comes from the I<required> list or the
206 I<dependencies> list.
207  
208 =item invalids
209  
210 This is a reference to an array which contains the name of the fields which
211 failed one or more of their constraint checks. If there are no invalid fields,
212 an empty arrayref will be returned.
213  
214 Fields defined with multiple constraints will have an array ref returned in the
215 @invalids array instead of a string. The first element in this array is the
216 name of the field, and the remaining fields are the names of the failed
217 constraints.
218  
219 =item unknowns
220  
221 This is a list of fields which are unknown to the profile. Whether or
222 not this indicates an error in the user input is application
223 dependent.
224  
225 =back
226  
227 =head2 new()
228  
229 Using C<new()> is only needed for advanced usage, including these cases:
230  
231 =over
232  
233 =item o
234  
235 Loading more than one profile at a time. Then you can select the profile you
236 want by name later with C<check()>. Here's an example:
237  
238 my $dfv = Data::FormValidator->new({
239 profile_1 => { # usual profile definition here },
240 profile_2 => { # another profile definition },
241 });
242  
243  
244 As illustrated, multiple profiles are defined through a hash ref whose keys point
245 to profile definitions.
246  
247 You can also load several profiles from a file, by defining several profiles as shown above
248 in an external file. Then just pass in the name of the file:
249  
250 my $dfv = Data::FormValidator->new('/path/to/profiles.pl');
251  
252 If the input profile is specified as a file name, the profiles will be reread
253 each time that the disk copy is modified.
254  
255 Now when calling C<check()>, you just need to supply the profile name:
256  
257 my $results = $dfv->check(\%input_hash,'profile_1');
258  
259 =item o
260  
261 Applying defaults to more than one input profile. There are some parts
262 of the validation profile that you might like to re-use for many form
263 validations.
264  
265 To facilitate this, C<new()> takes a second argument, a hash reference. Here
266 the usual input profile definitions can be made. These will act as defaults for
267 any subsequent calls to C<check()> on this object.
268  
269 Currently the logic for this is very simple. Any definition of a key in your
270 validation profile will completely overwrite your default value.
271  
272 This means you can't define two keys for C<constraint_regexp_map> and expect
273 they will always be there. This kind of feature may be added in the future.
274  
275 The exception here is definitions for your C<msgs> key. You will safely be
276 able to define some defaults for the top level keys within C<msgs> and not have
277 them clobbered just because C<msgs> was defined in a validation profile.
278  
279 One way to use this feature is to create your own sub-class that always provides
280 your defaults to C<new()>.
281  
282 Another option is to create your own wrapper routine which provides these defaults to
283 C<new()>. Here's an example of a routine you might put in a
284 L<CGI::Application|CGI::Application> super-class to make use of this feature:
285  
286 # Always use the built-in CGI object as the form data
287 # and provide some defaults to new constructor
288 sub check_form {
289 my $self = shift;
290 my $profile = shift
291 || die 'check_form: missing required profile';
292  
293 require Data::FormValidator;
294 my $dfv = Data::FormValidator->new({},{
295 # your defaults here
296 });
297 return $dfv->check($self->query,$profile);
298 }
299  
300  
301 =back
302  
303 =cut
304  
305 26 ▶sub validate {
Subroutine validate: called CC=2 SCAR=6.9
Pod documented
306 26 my ($self,$data,$name) = @_;
307  
308 26 my $data_set = $self->check( $data,$name );
309  
310 25 my $valid = $data_set->valid();
311 25 my $missing = $data_set->missing();
312 25 ▶ my $invalid = $data_set->{validate_invalid} || [];
Condition100%2/2
$data_set->{'validate_invalid'} || []
l!l
1312
MC/DC100%1/1
$data_set->{'validate_invalid'} || []
$data_set->{'validate_invalid'}
Truth table100%2/2
A
A= $data_set->{'validate_invalid'}
Aresult
11
00
313 25 my $unknown = [ $data_set->unknown ];
314  
315 25 return ( $valid, $missing, $invalid, $unknown );
316 }
317  
318 137 ▶sub check {
Subroutine check: called CC=7 SCAR=19.5
Pod documented
319 137 my ( $self, $data, $name ) = @_;
320  
321 # check can be used as a class method for simple cases
322 137 ▶ if (not ref $self) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $self) 95 42 137
323 95 my $class = $self;
324 95 $self = {};
325 95 bless $self, $class;
326 }
327  
328 137 my $profile;
329 137 ▶ if ( ref $name ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $name) { } 102 35 137
330 102 $profile = $name;
331 } else {
332 35 $self->load_profiles;
333 33 $profile = $self->{profiles}{$name};
334 33 ▶ die "No such profile $name\n" unless $profile;
Branch: 1 branch
BranchTrueFalseTotal
unless $profile 0 33 33
335 }
336 135 ▶ die "input profile must be a hash ref" unless ref $profile eq "HASH";
Branch: 1 branch
BranchTrueFalseTotal
unless ref $profile eq "HASH" 0 135 135
337  
338 # add in defaults from new(), if any
339 135 ▶ if ($self->{defaults}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"defaults"}) 14 121 135
340 14 $profile = { %{$self->{defaults}}, %$profile };
341 }
342  
343 # check the profile syntax or die with an error.
344 135 _check_profile_syntax($profile);
345  
346 127 my $results = Data::FormValidator::Results->new( $profile, $data );
347  
348 # As a special case, pass through any defaults for the 'msgs' key.
349 122 ▶ $results->msgs($self->{defaults}->{msgs}) if $self->{defaults}->{msgs};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"defaults"}{"msgs"} 2 120 122
350  
351 122 return $results;
352 }
353  
354 =head1 INPUT PROFILE SPECIFICATION
355  
356 An input profile is a hash reference containing one or more of the following
357 keys.
358  
359 Here is a very simple input profile. Examples of more advanced options are
360 described below.
361  
362 use Data::FormValidator::Constraints qw(:closures);
363  
364 my $profile = {
365 optional => [qw( company
366 fax
367 country )],
368  
369 required => [qw( fullname
370 phone
371 email
372 address )],
373  
374 constraint_methods => {
375 email => email(),
376 }
377 };
378  
379  
380 That defines some fields as optional, some as required, and defines that the
381 field named 'email' must pass the constraint named 'email'.
382  
383 Here is a complete list of the keys available in the input profile, with
384 examples of each.
385  
386 =head2 required
387  
388 This is an array reference which contains the name of the fields which are
389 required. Any fields in this list which are not present or contain only
390 spaces will be reported as missing.
391  
392 =head2 required_regexp
393  
394 required_regexp => qr/city|state|zipcode/,
395  
396 This is a regular expression used to specify additional field names for which values
397 will be required.
398  
399 =head2 require_some
400  
401 require_some => {
402 # require any two fields from this group
403 city_or_state_or_zipcode => [ 2, qw/city state zipcode/ ],
404 }
405  
406 This is a reference to a hash which defines groups of fields where 1 or more
407 fields from the group should be required, but exactly which fields doesn't
408 matter. The keys in the hash are the group names. These are returned as
409 "missing" unless the required number of fields from the group has been filled
410 in. The values in this hash are array references. The first element in this
411 array should be the number of fields in the group that is required. If the
412 first field in the array is not an a digit, a default of "1" will be used.
413  
414 =head2 optional
415  
416 optional => [qw/meat coffee chocolate/],
417  
418 This is an array reference which contains the name of optional fields.
419 These are fields which MAY be present and if they are, they will be
420 checked for valid input. Any fields not in optional or required list
421 will be reported as unknown.
422  
423 =head2 optional_regexp
424  
425 optional_regexp => qr/_province$/,
426  
427 This is a regular expression used to specify additional fields which are
428 optional. For example, if you wanted all fields names that begin with I<user_>
429 to be optional, you could use the regular expression, /^user_/
430  
431 =head2 dependencies
432  
433 dependencies => {
434  
435 # If cc_no is entered, make cc_type and cc_exp required
436 "cc_no" => [ qw( cc_type cc_exp ) ],
437  
438 # if pay_type eq 'check', require check_no
439 "pay_type" => {
440 check => [ qw( check_no ) ],
441 }
442  
443 # if cc_type is VISA or MASTERCARD require CVV
444 "cc_type" => sub {
445 my $dfv = shift;
446 my $type = shift;
447  
448 return [ 'cc_cvv' ] if ($type eq "VISA" || $type eq "MASTERCARD");
449 return [ ];
450 },
451 },
452  
453 This is for the case where an optional field has other requirements. The
454 dependent fields can be specified with an array reference.
455  
456 If the dependencies are specified with a hash reference then the additional
457 constraint is added that the optional field must equal a key for the
458 dependencies to be added.
459  
460 If the dependencies are specified as a code reference then the code will be
461 executed to determine the dependent fields. It is passed two parameters,
462 the object and the value of the field, and it should return an array reference
463 containing the list of dependent fields.
464  
465 Any fields in the dependencies list that are missing when the target is present
466 will be reported as missing.
467  
468 =head2 dependency_groups
469  
470 dependency_groups => {
471 # if either field is filled in, they all become required
472 password_group => [qw/password password_confirmation/],
473 }
474  
475 This is a hash reference which contains information about groups of
476 interdependent fields. The keys are arbitrary names that you create and
477 the values are references to arrays of the field names in each group.
478  
479 =head2 dependencies_regexp
480  
481 dependencies_regexp => {
482 qr/Line\d+\_ItemType$/ => sub {
483 my $dfv = shift;
484 my $itemtype = shift;
485 my $field = shift;
486  
487 if ($type eq 'NeedsBatteries') {
488 my ($prefix, $suffix) = split(/\_/, $field);
489  
490 return([$prefix . '_add_batteries]);
491 } else {
492 return([]);
493 }
494 },
495 },
496  
497 This is a regular expression used to specify additional fields which are
498 dependent. For example, if you wanted to add dependencies for all fields which
499 meet a certain criteria (such as multiple items in a shopping cart) where you
500 do not know before hand how many of such fields you may have.
501  
502 =head2 dependent_optionals
503  
504 dependent_optionals => {
505 # If delivery_address is specified then delivery_notes becomes optional
506 "delivery_address" => [ qw( delivery_notes ) ],
507  
508 # if delivery_type eq 'collection', collection_notes becomes optional
509 "delivery_type" => {
510 collection => [ qw( collection_notes ) ],
511 }
512  
513 # if callback_type is "phone" or "email" then additional_notes becomes optional
514 "callback_type" => sub {
515 my $dfv = shift;
516 my $type = shift;
517  
518 if ($type eq 'phone' || $type eq 'email') {
519 return(['additional_notes']);
520 } else {
521 return([]);
522 }
523 },
524 },
525  
526 This is for the case where an optional field can trigger other optional fields.
527 The dependent optional fields can be specified with an array reference.
528  
529 If the dependent optional fields are specified with a hash reference, then an
530 additional constraint is added that the optional field must equal a key for the
531 additional optional fields to be added.
532  
533 If the dependent optional fields are specified as a code reference then the
534 code will be executed to determine the additional optional fields. It is passed
535 two parameters, the object and the value of the field, and it should return an
536 array reference containing the list of additional optional fields.
537  
538 =head2 dependent_require_some
539  
540 dependent_require_some => {
541 # require any fields from this group if AddressID is "new"
542 AddressID => sub {
543 my $dfv = shift;
544 my $value = shift;
545  
546 if ($value eq 'new') {
547 return({
548 house_name_or_number => [ 1, 'HouseName', 'HouseNumber' ],
549 });
550 } else {
551 return;
552 }
553 },
554 }
555  
556 Sometimes a field will need to trigger additional dependencies but you only
557 require some of the fields. You cannot set them all to be dependent as you
558 might only have some of them, and you cannot set them all to be optional as
559 you must have some of them. This method allows you to specify this in a
560 similar way to the equire_some method but dependent upon other values. In
561 the example above if the AddressID submitted is "new" then at least 1 of
562 HouseName and HouseNumber must also be supplied. See require_some for the
563 valid options for the return.
564  
565 =head2 defaults
566  
567 defaults => {
568 country => "USA",
569 },
570  
571 This is a hash reference where keys are field names and
572 values are defaults to use if input for the field is missing.
573  
574 The values can be code refs which will be used to calculate the
575 value if needed. These code refs will be passed in the DFV::Results
576 object as the only parameter.
577  
578 The defaults are set shortly before the constraints are applied, and
579 will be returned with the other valid data.
580  
581 =head2 defaults_regexp_map
582  
583 defaults_regexp_map => {
584 qr/^opt_/ => 1,
585 },
586  
587 This is a hash reference that maps regular expressions to default values to
588 use for matching optional or required fields.
589  
590 It's useful if you have generated many checkbox fields with the similar names.
591 Since checkbox fields submit nothing at all when they are not checked, it's
592 useful to set defaults for them.
593  
594 Note that it doesn't make sense to use a default for a field handled by
595 C<optional_regexp> or C<required_regexp>. When the field is not submitted,
596 there is no way to know that it should be optional or required, and thus there's
597 no way to know that a default should be set for it.
598  
599 =head2 filters
600  
601 # trim leading and trailing whitespace on all fields
602 filters => ['trim'],
603  
604 This is a reference to an array of filters that will be applied to ALL optional
605 and required fields, B<before> any constraints are applied.
606  
607 This can be the name of a built-in filter
608 (trim,digit,etc) or an anonymous subroutine which should take one parameter,
609 the field value and return the (possibly) modified value.
610  
611 Filters modify the data returned through the results object, so use them carefully.
612  
613 See L<Data::FormValidator::Filters> for details on the built-in filters.
614  
615 =head2 field_filters
616  
617 field_filters => {
618 cc_no => ['digit'],
619 },
620  
621 A hash ref with field names as keys. Values are array references of built-in
622 filters to apply (trim,digit,etc) or an anonymous subroutine which should take
623 one parameter, the field value and return the (possibly) modified value.
624  
625 Filters are applied B<before> any constraints are applied.
626  
627 See L<Data::FormValidator::Filters> for details on the built-in filters.
628  
629 =head2 field_filter_regexp_map
630  
631 field_filter_regexp_map => {
632 # Upper-case the first letter of all fields that end in "_name"
633 qr/_name$/ => ['ucfirst'],
634 },
635  
636 'field_filter_regexp_map' is used to apply filters to fields that match a
637 regular expression. This is a hash reference where the keys are the regular
638 expressions to use and the values are references to arrays of filters which
639 will be applied to specific input fields. Just as with 'field_filters', you
640 can you use a built-in filter or use a coderef to supply your own.
641  
642 =head2 constraint_methods
643  
644 use Data::FormValidator::Constraints qw(:closures);
645  
646 constraint_methods => {
647 cc_no => cc_number({fields => ['cc_type']}),
648 cc_type => cc_type(),
649 cc_exp => cc_exp(),
650 },
651  
652 A hash ref which contains the constraints that will be used to check whether or
653 not the field contains valid data.
654  
655 B<Note:> To use the built-in constraints, they need to first be loaded into your
656 name space using the syntax above. (Unless you are using the old C<constraints> key,
657 documented in L<BACKWARDS COMPATIBILITY>).
658  
659 The keys in this hash are field names. The values can be any of the following:
660  
661 =over
662  
663 =item o
664  
665 A named constraint.
666  
667 B<Example>:
668  
669 my_zipcode_field => zip(),
670  
671 See L<Data::FormValidator::Constraints> for the details of which
672 built-in constraints that are available.
673  
674  
675 =item o
676  
677 A perl regular expression
678  
679 B<Example>:
680  
681 my_zipcode_field => qr/^\d{5}$/, # match exactly 5 digits
682  
683 If this field is named in C<untaint_constraint_fields> or C<untaint_regexp_map>,
684 or C<untaint_all_constraints> is effective, be aware of the following: If you
685 write your own regular expressions and only match part of the string then
686 you'll only get part of the string in the valid hash. It is a good idea to
687 write you own constraints like /^regex$/. That way you match the whole string.
688  
689 =item o
690  
691 a subroutine reference, to supply custom code
692  
693 This will check the input and return true or false depending on the input's validity.
694 By default, the constraint function receives a L<Data::FormValidator::Results>
695 object as its first argument, and the value to be validated as the second. To
696 validate a field based on more inputs than just the field itself, see
697 L<VALIDATING INPUT BASED ON MULTIPLE FIELDS>.
698  
699 B<Examples>:
700  
701 # Notice the use of 'pop'--
702 # the object is the first arg passed to the method
703 # while the value is the second, and last arg.
704 my_zipcode_field => sub { my $val = pop; return $val =~ '/^\d{5}$/' },
705  
706 # OR you can reference a subroutine, which should work like the one above
707 my_zipcode_field => \&my_validation_routine,
708  
709 # An example of setting the constraint name.
710 my_zipcode_field => sub {
711 my ($dfv, $val) = @_;
712 $dfv->set_current_constraint_name('my_constraint_name');
713 return $val =~ '/^\d{5}$/'
714 },
715  
716 =item o
717  
718 an array reference
719  
720 An array reference is used to apply multiple constraints to a single
721 field. Any of the above options are valid entries the array.
722 See L<MULTIPLE CONSTRAINTS> below.
723  
724 For more details see L<VALIDATING INPUT BASED ON MULTIPLE FIELDS>.
725  
726 =back
727  
728 =head2 constraint_method_regexp_map
729  
730 use Data::FormValidator::Constraints qw(:closures);
731  
732 # In your profile.
733 constraint_method_regexp_map => {
734 # All fields that end in _postcode have the 'postcode' constraint applied.
735 qr/_postcode$/ => postcode(),
736 },
737  
738 A hash ref where the keys are the regular expressions to
739 use and the values are the constraints to apply.
740  
741 If one or more constraints have already been defined for a given field using
742 C<constraint_methods>, C<constraint_method_regexp_map> will add an additional
743 constraint for that field for each regular expression that matches.
744  
745 =head2 untaint_all_constraints
746  
747 untaint_all_constraints => 1,
748  
749 If this field is set, all form data that passes a constraint will be untainted.
750 The untainted data will be returned in the valid hash. Untainting is based on
751 the pattern match used by the constraint. Note that some constraint routines
752 may not provide untainting.
753  
754 See L<Writing your own constraint routines|Data::FormValidator::Constraints/"WRITING YOUR OWN CONSTRAINT ROUTINES"> for more information.
755  
756 This is overridden by C<untaint_constraint_fields> and C<untaint_regexp_map>.
757  
758 =head2 untaint_constraint_fields
759  
760 untaint_constraint_fields => [qw(zipcode state)],
761  
762 Specifies that one or more fields will be untainted if they pass their
763 constraint(s). This can be set to a single field name or an array reference of
764 field names. The untainted data will be returned in the valid hash.
765  
766 This overrides the untaint_all_constraints flag.
767  
768 =head2 untaint_regexp_map
769  
770 untaint_regexp_map => [qr/some_field_\d/],
771  
772 Specifies that certain fields will be untainted if they pass their constraints
773 and match one of the regular expressions supplied. This can be set to a single
774 regex, or an array reference of regexes. The untainted data will be returned
775 in the valid hash.
776  
777 The above example would untaint the fields named C<some_field_1>, and C<some_field_2>
778 but not C<some_field>.
779  
780 This overrides the untaint_all_constraints flag.
781  
782 =head2 missing_optional_valid
783  
784 missing_optional_valid => 1
785  
786 This can be set to a true value to cause optional fields with empty values to
787 be included in the valid hash. By default they are not included-- this is the
788 historical behavior.
789  
790 This is an important flag if you are using the contents of an "update" form to
791 update a record in a database. Without using the option, fields that have been
792 set back to "blank" may fail to get updated.
793  
794 =head2 validator_packages
795  
796 # load all the constraints and filters from these modules
797 validator_packages => [qw(Data::FormValidator::Constraints::Upload)],
798  
799 This key is used to define other packages which contain constraint routines or
800 filters. Set this key to a single package name, or an arrayref of several. All
801 of its constraint and filter routines beginning with 'match_', 'valid_' and
802 'filter_' will be imported into Data::FormValidator. This lets you reference
803 them in a constraint with just their name, just like built-in routines. You
804 can even override the provided validators.
805  
806 See L<Writing your own constraint routines|Data::FormValidator::Constraints/"WRITING YOUR OWN CONSTRAINT ROUTINES">
807 documentation for more information
808  
809 =head2 msgs
810  
811 This key is used to define parameters related to formatting error messages
812 returned to the user.
813  
814 By default, invalid fields have the message "Invalid" associated with them
815 while missing fields have the message "Missing" associated with them.
816  
817 In the simplest case, nothing needs to be defined here, and the default values
818 will be used.
819  
820 The default formatting applied is designed for display in an XHTML web page.
821 That formatting is as followings:
822  
823 <span style="color:red;font-weight:bold" class="dfv_errors">* %s</span>
824  
825 The C<%s> will be replaced with the message. The effect is that the message
826 will appear in bold red with an asterisk before it. This style can be overridden by simply
827 defining "dfv_errors" appropriately in a style sheet, or by providing a new format string.
828  
829 Here's a more complex example that shows how to provide your own default message strings, as well
830 as providing custom messages per field, and handling multiple constraints:
831  
832 msgs => {
833  
834 # set a custom error prefix, defaults to none
835 prefix=> 'error_',
836  
837 # Set your own "Missing" message, defaults to "Missing"
838 missing => 'Not Here!',
839  
840 # Default invalid message, default's to "Invalid"
841 invalid => 'Problematic!',
842  
843 # message separator for multiple messages
844 # Defaults to ' '
845 invalid_separator => ' <br /> ',
846  
847 # formatting string, default given above.
848 format => 'ERROR: %s',
849  
850 # Error messages, keyed by constraint name
851 # Your constraints must be named to use this.
852 constraints => {
853 'date_and_time' => 'Not a valid time format',
854 # ...
855 },
856  
857 # This token will be included in the hash if there are
858 # any errors returned. This can be useful with templating
859 # systems like HTML::Template
860 # The 'prefix' setting does not apply here.
861 # defaults to undefined
862 any_errors => 'some_errors',
863 }
864  
865 The hash that's prepared can be retrieved through the C<msgs> method
866 described in the L<Data::FormValidator::Results> documentation.
867  
868 =head2 msgs - callback
869  
870 I<This is a new feature. While it expected to be forward-compatible, it hasn't
871 yet received the testing the rest of the API has.>
872  
873 If the built-in message generation doesn't suit you, it is also possible to
874 provide your own by specifying a code reference:
875  
876 msgs => \&my_msgs_callback
877  
878 This will be called as a L<Data::FormValidator::Results> method. It may
879 receive as arguments an additional hash reference of control parameters,
880 corresponding to the key names usually used in the C<msgs> area of the
881 profile. You can ignore this information if you'd like.
882  
883 If you have an alternative error message handler you'd like to share, stick in
884 the C<Data::FormValidator::ErrMsgs> name space and upload it to CPAN.
885  
886 =head2 debug
887  
888 This method is used to print details about what is going on to STDERR.
889  
890 Currently only level '1' is used. It provides information about which
891 fields matched constraint_regexp_map.
892  
893 =head2 A shortcut for array refs
894  
895 A number of parts of the input profile specification include array references
896 as their values. In any of these places, you can simply use a string if you
897 only need to specify one value. For example, instead of
898  
899 filters => [ 'trim' ]
900  
901 you can simply say
902  
903 filters => 'trim'
904  
905 =head2 A note on regular expression formats
906  
907 In addition to using the preferred method of defining regular expressions
908 using C<qr>, a deprecated style of defining them as strings is also supported.
909  
910 Preferred:
911  
912 qr/this is great/
913  
914 Deprecated, but supported
915  
916 'm/this still works/'
917  
918 =head1 VALIDATING INPUT BASED ON MULTIPLE FIELDS
919  
920 You can pass more than one value into a constraint routine. For that, the
921 value of the constraint should be a hash reference. If you are creating your
922 own routines, be sure to read the section labeled
923 L<WRITING YOUR OWN CONSTRAINT ROUTINES>,
924 in the Data::FormValidator::Constraints documentation. It describes
925 a newer and more flexible syntax.
926  
927 Using the original syntax, one key should be named C<constraint> and should
928 have a value set to the reference of the subroutine or the name of a built-in
929 validator. Another required key is C<params>. The value of the C<params> key
930 is a reference to an array of the other elements to use in the validation. If
931 the element is a scalar, it is assumed to be a field name. The field is known
932 to Data::FormValidator, the value will be filtered through any defined filters
933 before it is passed in. If the value is a reference, the reference is passed
934 directly to the routine. Don't forget to include the name of the field to
935 check in that list, if you are using this syntax.
936  
937 B<Example>:
938  
939 cc_no => {
940 constraint => "cc_number",
941 params => [ qw( cc_no cc_type ) ],
942 },
943  
944  
945 =head1 MULTIPLE CONSTRAINTS
946  
947 Multiple constraints can be applied to a single field by defining the value of
948 the constraint to be an array reference. Each of the values in this array can
949 be any of the constraint types defined above.
950  
951 When using multiple constraints it is important to return the name of the
952 constraint that failed so you can distinguish between them. To do that,
953 either use a named constraint, or use the hash ref method of defining a
954 constraint and include a C<name> key with a value set to the name of your
955 constraint. Here's an example:
956  
957 my_zipcode_field => [
958 'zip',
959 {
960 constraint_method => '/^406/',
961 name => 'starts_with_406',
962 }
963 ],
964  
965 You can use an array reference with a single constraint in it if you just want
966 to have the name of your failed constraint returned in the above fashion.
967  
968 Read about the C<validate()> function above to see how multiple constraints
969 are returned differently with that method.
970  
971 =cut
972  
973 35 ▶sub load_profiles {
Subroutine load_profiles: called CC=7 SCAR=19.8
Pod undocumented
974 35 my $self = shift;
975  
976 35 my $file = $self->{profile_file};
977 35 ▶ return unless $file;
Branch: 1 branch
BranchTrueFalseTotal
unless $file 32 3 35
978  
979 3 ▶ die "No such file: $file\n" unless -f $file;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $file 1 2 3
980 2 ▶ die "Can't read $file\n" unless -r _;
Branch: 1 branch
BranchTrueFalseTotal
unless -r _ 0 2 2
981  
982 2 my $mtime = (stat _)[9];
983 2 ▶ return if $self->{profiles} and $self->{profiles_mtime} <= $mtime;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"profiles"} and $self->{"profiles_mtime"} <= $mtime 0 2 2
Condition33%1/3
$self->{"profiles"} and $self->{"profiles_mtime"} <= $mtime
!ll&&!rl&&r
200
MC/DC0%0/2
$self->{"profiles"} and $self->{"profiles_mtime"} <= $mtime
$self->{"profiles"} $self->{"profiles_mtime"} <= $mtime
Truth table33%1/3
A and B
A= $self->{"profiles"}B= $self->{"profiles_mtime"} <= $mtime
ABresult
0X0
100
111
984  
985 2 $self->{profiles} = do $file;
986 die "Input profiles didn't return a hash ref: $@\n"
987 2 ▶ unless ref $self->{profiles} eq "HASH";
Branch: 1 branch
BranchTrueFalseTotal
unless ref $self->{"profiles"} eq "HASH" 1 1 2
988  
989 1 $self->{profiles_mtime} = $mtime;
990 }
991  
992  
993  
994 # check the profile syntax and die if we have an error
995 135 ▶sub _check_profile_syntax {
Subroutine _check_profile_syntax: called CC=20 SCAR=30.0
996 135 my $profile = shift;
997  
998 135 ▶ (ref $profile eq 'HASH') or
Branch: 1 branch
BranchTrueFalseTotal
ref $profile eq "HASH" or die "Invalid input profile: needs to be a hash reference\n" 135 0 135
999 die "Invalid input profile: needs to be a hash reference\n";
1000  
1001 135 my @invalid;
1002  
1003 # check top level keys
1004 {
1005 135 my @valid_profile_keys = (qw/
1006 constraint_methods
1007 constraint_method_regexp_map
1008 constraint_regexp_map
1009 constraints
1010 defaults
1011 defaults_regexp_map
1012 dependencies
1013 dependencies_regexp
1014 dependency_groups
1015 dependent_optionals
1016 dependent_require_some
1017 field_filter_regexp_map
1018 field_filters
1019 filters
1020 missing_optional_valid
1021 msgs
1022 optional
1023 optional_regexp
1024 require_some
1025 required
1026 required_regexp
1027 untaint_all_constraints
1028 validator_packages
1029 untaint_constraint_fields
1030 untaint_regexp_map
1031 debug
1032 /);
1033  
1034 # If any of the keys in the profile are not listed as
1035 # valid keys here, we die with an error
1036 135 for my $key (keys %$profile) {
1037 720 ▶ push @invalid, $key unless grep $key eq $_, @valid_profile_keys;
Branch: 1 branch
BranchTrueFalseTotal
unless grep(($key eq $_), @valid_profile_keys) 3 717 720
1038 }
1039  
1040 135 local $" = ', ';
1041 135 ▶ if (@invalid) {
Branch: 1 branch
BranchTrueFalseTotal
if (@invalid) 2 133 135
1042 2 die "Invalid input profile: keys not recognised [@invalid]\n";
1043 }
1044 }
1045  
1046 # Check that constraint_methods are always code refs or REs
1047 {
1048 # Cases:
1049 # 1. constraint_methods => { field => func() }
1050 # 2. constraint_methods => { field => [ func() ] }
1051 # 3. constraint_method_regex_map => { qr/^field/ => func() }
1052 # 4. constraint_method_regex_map => { qr/^field/ => [ func() ] }
1053 # 5. constraint_methods => { field => { constraint_method => func() } }
1054  
1055 # Could be improved by also naming the associated key for the bad value.
1056 135 for my $key (grep { $profile->{$_} } qw/constraint_methods constraint_method_regexp_map/) {
1057 99 for my $val (map { _arrayify($_) } values %{ $profile->{$key} }) {
1058 69 ▶ if (ref $val eq 'HASH' && !grep(ref $val->{constraint_method} eq $_, 'CODE','Regexp')) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $val eq 'HASH' and not grep((ref $val->{'constraint_method'} eq $_), 'CODE', 'Regexp')) { } 1 68 69
elsif (not grep((ref $val eq $_), 'HASH', 'CODE', 'Regexp')) { } 2 66 68
Condition100%3/3
ref $val eq "HASH" and not grep((ref $val->{"constraint_method"} eq $_), "CODE", "Regexp")
!ll&&!rl&&r
6621
MC/DC100%2/2
ref $val eq "HASH" and not grep((ref $val->{"constraint_method"} eq $_), "CODE", "Regexp")
ref $val eq "HASH" not grep((ref $val->{"constraint_method"} eq $_), "CODE", "Regexp")
Truth table100%3/3
A and not(B)
A= ref $val eq "HASH"B= not grep((ref $val->{"constraint_method"} eq $_), "CODE", "Regexp")
ABresult
0X0
100
111
1059 1 die "Value for constraint_method within hashref '$val->{constraint_method}' not a code reference or Regexp . Do you need func(), not 'func'?";
1060 }
1061 # Cases 1 through 4.
1062 elsif (!grep(ref $val eq $_, 'HASH','CODE','Regexp')) {
1063 2 die "Value for constraint_method '$val' not a code reference or Regexp . Do you need func(), not 'func'?";
1064 }
1065 # Case 5.
1066 else {
1067 # We're cool. Nothing to do.
1068 }
1069 }
1070 }
1071 }
1072  
1073 # Check constraint hash keys
1074 {
1075 133 my @valid_constraint_hash_keys = (qw/
1076 constraint
1077 constraint_method
1078 name
1079 params
1080 /);
1081  
1082 66 my @constraint_hashrefs = grep { ref $_ eq 'HASH' } values %{ $profile->{constraints} }
1083 130 ▶ if $profile->{constraints};
Branch: 1 branch
BranchTrueFalseTotal
if $profile->{"constraints"} 69 61 130
1084 12 push @constraint_hashrefs, grep { ref $_ eq 'HASH' } values %{ $profile->{constraint_regexp_map} }
1085 130 ▶ if $profile->{constraint_regexp_map};
Branch: 1 branch
BranchTrueFalseTotal
if $profile->{"constraint_regexp_map"} 44 86 130
1086  
1087 130 for my $href (@constraint_hashrefs) {
1088 28 for my $key (keys %$href) {
1089 56 ▶ push @invalid, $key unless grep $key eq $_, @valid_constraint_hash_keys;
Branch: 1 branch
BranchTrueFalseTotal
unless grep(($key eq $_), @valid_constraint_hash_keys) 2 54 56
1090 }
1091 }
1092  
1093 130 ▶ if (@invalid) {
Branch: 1 branch
BranchTrueFalseTotal
if (@invalid) 2 128 130
1094 2 die "Invalid input profile: constraint hashref keys not recognised [@invalid]\n";
1095 }
1096 }
1097  
1098 # Check msgs keys
1099 {
1100 130 my @valid_msgs_hash_keys = (qw/
1101 prefix
1102 missing
1103 invalid
1104 invalid_separator
1105 invalid_seperator
1106 format
1107 constraints
1108 any_errors
1109 /);
1110 128 ▶ if (ref $profile->{msgs} eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $profile->{"msgs"} eq "HASH") 15 113 128
1111 15 for my $key (keys %{ $profile->{msgs} }) {
1112 17 ▶ push @invalid, $key unless grep $key eq $_, @valid_msgs_hash_keys;
Branch: 1 branch
BranchTrueFalseTotal
unless grep(($key eq $_), @valid_msgs_hash_keys) 1 16 17
1113 }
1114 }
1115 128 ▶ if (@invalid) {
Branch: 1 branch
BranchTrueFalseTotal
if (@invalid) 1 127 128
1116 1 die "Invalid input profile: msgs keys not recognized: [@invalid]\n";
1117 }
1118 }
1119  
1120 }
1121  
1122  
1123 59 1;
1124  
1125 __END__
« blib/lib/Data/FormValidator/Constraints/Upload.pm ↑ Summary blib/lib/Data/FormValidator/Constraints.pm »