File Coverage

blib/lib/Data/FormValidator.pm
Criterion Covered Total %
statement 110 110 100.0
branch 47 52 90.3
condition 7 11 63.6
subroutine 13 14 92.8
pod 3 4 75.0
total 180 191 94.2


line stmt bran cond sub pod time code
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
8             # Maintainer: David Farrell
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 61     61   3007630 use Exporter 'import';
  61         153  
  61         2171  
27 61     61   353 use File::Spec qw();
  61         130  
  61         847  
28 61     61   1265 use 5.008;
  61         211  
29              
30 61     61   23629 use Data::FormValidator::Results;
  61         181  
  61         3150  
31             *_arrayify = \&Data::FormValidator::Results::_arrayify;
32 61     61   416 use Data::FormValidator::Filters ':filters';
  61         139  
  61         11848  
33 61     61   421 use Data::FormValidator::Constraints qw(:validators :matchers);
  61         140  
  61         478  
34              
35             our $VERSION = 4.88;
36              
37             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             our @EXPORT_OK = (@{ $EXPORT_TAGS{filters} }, @{ $EXPORT_TAGS{validators} }, @{ $EXPORT_TAGS{matchers} });
89              
90              
91 61     61   456 use strict;
  61         182  
  61         1353  
92 61     61   301 use Symbol;
  61         144  
  61         63972  
93              
94              
95       0     sub DESTROY {}
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             sub new {
134 43     43 1 79092 my $proto = shift;
135 43         91 my $profiles_or_file = shift;
136 43         85 my $defaults = shift;
137              
138 43   33     236 my $class = ref $proto || $proto;
139              
140 43 100       181 if ($defaults) {
141 4 100       24 ref $defaults eq 'HASH' or
142             die 'second argument to new must be a hash ref';
143             }
144              
145 42         88 my ($file, $profiles);
146              
147 42 100       141 if (ref $profiles_or_file) {
148 39         73 $profiles = $profiles_or_file;
149             }
150             else {
151 3         90 $file = File::Spec->rel2abs( $profiles_or_file );
152             }
153              
154              
155 42         252 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 is the recommended method to use to validate forms. It returns its results as a
169             L object. A
170             deprecated method C 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 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 provides a deprecated alternative to C. 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 list or the
206             I 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 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. 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, 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 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 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 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 key. You will safely be
276             able to define some defaults for the top level keys within C and not have
277             them clobbered just because C 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.
281              
282             Another option is to create your own wrapper routine which provides these defaults to
283             C. Here's an example of a routine you might put in a
284             L 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             sub validate {
306 32     32 1 38123 my ($self,$data,$name) = @_;
307              
308 32         132 my $data_set = $self->check( $data,$name );
309              
310 31         162 my $valid = $data_set->valid();
311 31         231 my $missing = $data_set->missing();
312 31   100     136 my $invalid = $data_set->{validate_invalid} || [];
313 31         126 my $unknown = [ $data_set->unknown ];
314              
315 31         344 return ( $valid, $missing, $invalid, $unknown );
316             }
317              
318             sub check {
319 159     159 1 167477 my ( $self, $data, $name ) = @_;
320              
321             # check can be used as a class method for simple cases
322 159 100       523 if (not ref $self) {
323 99         232 my $class = $self;
324 99         211 $self = {};
325 99         237 bless $self, $class;
326             }
327              
328 159         311 my $profile;
329 159 100       965 if ( ref $name ) {
330 106         252 $profile = $name;
331             } else {
332 53         201 $self->load_profiles;
333 51         111 $profile = $self->{profiles}{$name};
334 51 50       142 die "No such profile $name\n" unless $profile;
335             }
336 157 50       527 die "input profile must be a hash ref" unless ref $profile eq "HASH";
337              
338             # add in defaults from new(), if any
339 157 100       578 if ($self->{defaults}) {
340 21         35 $profile = { %{$self->{defaults}}, %$profile };
  21         197  
341             }
342              
343             # check the profile syntax or die with an error.
344 157         797 _check_profile_syntax($profile);
345              
346 149         864 my $results = Data::FormValidator::Results->new( $profile, $data );
347              
348             # As a special case, pass through any defaults for the 'msgs' key.
349 144 100       499 $results->msgs($self->{defaults}->{msgs}) if $self->{defaults}->{msgs};
350              
351 144         780 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
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 or C. 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 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 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 any constraints are applied.
626              
627             See L 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 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 key,
657             documented in L).
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:
668              
669             my_zipcode_field => zip(),
670              
671             See L 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:
680              
681             my_zipcode_field => qr/^\d{5}$/, # match exactly 5 digits
682              
683             If this field is named in C or C,
684             or C 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
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.
698              
699             B:
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 below.
723              
724             For more details see L.
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, C 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 for more information.
755              
756             This is overridden by C and C.
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, and C
778             but not C.
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
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             * %s
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 => '
',
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 method
866             described in the L documentation.
867              
868             =head2 msgs - callback
869              
870             I
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 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 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 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, 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,
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 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. The value of the C 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:
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 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 function above to see how multiple constraints
969             are returned differently with that method.
970              
971             =cut
972              
973             sub load_profiles {
974 53     53 0 157 my $self = shift;
975              
976 53         213 my $file = $self->{profile_file};
977 53 100       196 return unless $file;
978              
979 3 100       52 die "No such file: $file\n" unless -f $file;
980 2 50       9 die "Can't read $file\n" unless -r _;
981              
982 2         7 my $mtime = (stat _)[9];
983 2 50 33     8 return if $self->{profiles} and $self->{profiles_mtime} <= $mtime;
984              
985 2         494 $self->{profiles} = do $file;
986             die "Input profiles didn't return a hash ref: $@\n"
987 2 100       15 unless ref $self->{profiles} eq "HASH";
988              
989 1         32 $self->{profiles_mtime} = $mtime;
990             }
991              
992              
993              
994             # check the profile syntax and die if we have an error
995             sub _check_profile_syntax {
996 157     157   354 my $profile = shift;
997              
998 157 50       457 (ref $profile eq 'HASH') or
999             die "Invalid input profile: needs to be a hash reference\n";
1000              
1001 157         268 my @invalid;
1002              
1003             # check top level keys
1004             {
1005 157         894 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 157         589 for my $key (keys %$profile) {
1037 859 100       3065 push @invalid, $key unless grep $key eq $_, @valid_profile_keys;
1038             }
1039              
1040 157         384 local $" = ', ';
1041 157 100       556 if (@invalid) {
1042 2         20 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 157         4148 for my $key (grep { $profile->{$_} } qw/constraint_methods constraint_method_regexp_map/) {
  155         309  
  310         732  
1057 120         197 for my $val (map { _arrayify($_) } values %{ $profile->{$key} }) {
  79         217  
  120         299  
1058 83 100 100     393 if (ref $val eq 'HASH' && !grep(ref $val->{constraint_method} eq $_, 'CODE','Regexp')) {
    100          
1059 1         9 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         19 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 155         254 my @valid_constraint_hash_keys = (qw/
  152         424  
1076             constraint
1077             constraint_method
1078             name
1079             params
1080             /);
1081              
1082 77         242 my @constraint_hashrefs = grep { ref $_ eq 'HASH' } values %{ $profile->{constraints} }
  81         228  
1083 152 100       432 if $profile->{constraints};
1084 14         44 push @constraint_hashrefs, grep { ref $_ eq 'HASH' } values %{ $profile->{constraint_regexp_map} }
  53         110  
1085 152 100       412 if $profile->{constraint_regexp_map};
1086              
1087 152         356 for my $href (@constraint_hashrefs) {
1088 38         121 for my $key (keys %$href) {
1089 76 100       231 push @invalid, $key unless grep $key eq $_, @valid_constraint_hash_keys;
1090             }
1091             }
1092              
1093 152 100       416 if (@invalid) {
1094 2         13 die "Invalid input profile: constraint hashref keys not recognised [@invalid]\n";
1095             }
1096             }
1097              
1098             # Check msgs keys
1099             {
1100 152         237 my @valid_msgs_hash_keys = (qw/
  150         239  
  150         444  
1101             prefix
1102             missing
1103             invalid
1104             invalid_separator
1105             invalid_seperator
1106             format
1107             constraints
1108             any_errors
1109             /);
1110 150 100       419 if (ref $profile->{msgs} eq 'HASH') {
1111 15         31 for my $key (keys %{ $profile->{msgs} }) {
  15         59  
1112 17 100       76 push @invalid, $key unless grep $key eq $_, @valid_msgs_hash_keys;
1113             }
1114             }
1115 150 100       453 if (@invalid) {
1116 1         10 die "Invalid input profile: msgs keys not recognized: [@invalid]\n";
1117             }
1118             }
1119              
1120             }
1121              
1122              
1123             1;
1124              
1125             __END__