File Coverage

blib/lib/Data/FormValidator.pm
Criterion Covered Total %
statement 107 107 100.0
branch 47 52 90.3
condition 7 11 63.6
subroutine 12 13 92.3
pod 3 4 75.0
total 176 187 94.1


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