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 59     59   813209 use Exporter 'import';
  59         87  
  59         1902  
27 59     59   1573 use 5.008;
  59         138  
28              
29 59     59   26623 use Data::FormValidator::Results;
  59         95  
  59         2150  
30             *_arrayify = \&Data::FormValidator::Results::_arrayify;
31 59     59   259 use Data::FormValidator::Filters ':filters';
  59         56  
  59         9528  
32 59     59   253 use Data::FormValidator::Constraints qw(:validators :matchers);
  59         61  
  59         329  
33              
34             our $VERSION = 4.85;
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 59     59   265 use strict;
  59         71  
  59         990  
91 59     59   181 use Symbol;
  59         65  
  59         52270  
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 32     32 1 7039 my $proto = shift;
134 32         45 my $profiles_or_file = shift;
135 32         44 my $defaults = shift;
136              
137 32   33     151 my $class = ref $proto || $proto;
138              
139 32 100       80 if ($defaults) {
140 4 100       16 ref $defaults eq 'HASH' or
141             die 'second argument to new must be a hash ref';
142             }
143              
144 31         45 my ($file, $profiles);
145              
146 31 100       83 if (ref $profiles_or_file) {
147 28         42 $profiles = $profiles_or_file;
148             }
149             else {
150 3         4 $file = $profiles_or_file;
151             }
152              
153              
154 31         135 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 26     26 1 1769 my ($self,$data,$name) = @_;
306              
307 26         67 my $data_set = $self->check( $data,$name );
308              
309 25         98 my $valid = $data_set->valid();
310 25         87 my $missing = $data_set->missing();
311 25   100     108 my $invalid = $data_set->{validate_invalid} || [];
312 25         95 my $unknown = [ $data_set->unknown ];
313              
314 25         253 return ( $valid, $missing, $invalid, $unknown );
315             }
316              
317             sub check {
318 137     137 1 82540 my ( $self, $data, $name ) = @_;
319              
320             # check can be used as a class method for simple cases
321 137 100       360 if (not ref $self) {
322 95         146 my $class = $self;
323 95         209 $self = {};
324 95         185 bless $self, $class;
325             }
326              
327 137         646 my $profile;
328 137 100       352 if ( ref $name ) {
329 102         123 $profile = $name;
330             } else {
331 35         149 $self->load_profiles;
332 33         61 $profile = $self->{profiles}{$name};
333 33 50       89 die "No such profile $name\n" unless $profile;
334             }
335 135 50       371 die "input profile must be a hash ref" unless ref $profile eq "HASH";
336              
337             # add in defaults from new(), if any
338 135 100       417 if ($self->{defaults}) {
339 14         17 $profile = { %{$self->{defaults}}, %$profile };
  14         82  
340             }
341              
342             # check the profile syntax or die with an error.
343 135         357 _check_profile_syntax($profile);
344              
345 127         616 my $results = Data::FormValidator::Results->new( $profile, $data );
346              
347             # As a special case, pass through any defaults for the 'msgs' key.
348 122 100       357 $results->msgs($self->{defaults}->{msgs}) if $self->{defaults}->{msgs};
349              
350 122         344 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 defaults
479              
480             defaults => {
481             country => "USA",
482             },
483              
484             This is a hash reference where keys are field names and
485             values are defaults to use if input for the field is missing.
486              
487             The values can be code refs which will be used to calculate the
488             value if needed. These code refs will be passed in the DFV::Results
489             object as the only parameter.
490              
491             The defaults are set shortly before the constraints are applied, and
492             will be returned with the other valid data.
493              
494             =head2 defaults_regexp_map
495              
496             defaults_regexp_map => {
497             qr/^opt_/ => 1,
498             },
499              
500             This is a hash reference that maps regular expressions to default values to
501             use for matching optional or required fields.
502              
503             It's useful if you have generated many checkbox fields with the similar names.
504             Since checkbox fields submit nothing at all when they are not checked, it's
505             useful to set defaults for them.
506              
507             Note that it doesn't make sense to use a default for a field handled by
508             C or C. When the field is not submitted,
509             there is no way to know that it should be optional or required, and thus there's
510             no way to know that a default should be set for it.
511              
512             =head2 filters
513              
514             # trim leading and trailing whitespace on all fields
515             filters => ['trim'],
516              
517             This is a reference to an array of filters that will be applied to ALL optional
518             and required fields, B any constraints are applied.
519              
520             This can be the name of a built-in filter
521             (trim,digit,etc) or an anonymous subroutine which should take one parameter,
522             the field value and return the (possibly) modified value.
523              
524             Filters modify the data returned through the results object, so use them carefully.
525              
526             See L for details on the built-in filters.
527              
528             =head2 field_filters
529              
530             field_filters => {
531             cc_no => ['digit'],
532             },
533              
534             A hash ref with field names as keys. Values are array references of built-in
535             filters to apply (trim,digit,etc) or an anonymous subroutine which should take
536             one parameter, the field value and return the (possibly) modified value.
537              
538             Filters are applied B any constraints are applied.
539              
540             See L for details on the built-in filters.
541              
542             =head2 field_filter_regexp_map
543              
544             field_filter_regexp_map => {
545             # Upper-case the first letter of all fields that end in "_name"
546             qr/_name$/ => ['ucfirst'],
547             },
548              
549             'field_filter_regexp_map' is used to apply filters to fields that match a
550             regular expression. This is a hash reference where the keys are the regular
551             expressions to use and the values are references to arrays of filters which
552             will be applied to specific input fields. Just as with 'field_filters', you
553             can you use a built-in filter or use a coderef to supply your own.
554              
555             =head2 constraint_methods
556              
557             use Data::FormValidator::Constraints qw(:closures);
558              
559             constraint_methods => {
560             cc_no => cc_number({fields => ['cc_type']}),
561             cc_type => cc_type(),
562             cc_exp => cc_exp(),
563             },
564              
565             A hash ref which contains the constraints that will be used to check whether or
566             not the field contains valid data.
567              
568             B To use the built-in constraints, they need to first be loaded into your
569             name space using the syntax above. (Unless you are using the old C key,
570             documented in L).
571              
572             The keys in this hash are field names. The values can be any of the following:
573              
574             =over
575              
576             =item o
577              
578             A named constraint.
579              
580             B:
581              
582             my_zipcode_field => zip(),
583              
584             See L for the details of which
585             built-in constraints that are available.
586              
587              
588             =item o
589              
590             A perl regular expression
591              
592             B:
593              
594             my_zipcode_field => qr/^\d{5}$/, # match exactly 5 digits
595              
596             If this field is named in C or C,
597             or C is effective, be aware of the following: If you
598             write your own regular expressions and only match part of the string then
599             you'll only get part of the string in the valid hash. It is a good idea to
600             write you own constraints like /^regex$/. That way you match the whole string.
601              
602             =item o
603              
604             a subroutine reference, to supply custom code
605              
606             This will check the input and return true or false depending on the input's validity.
607             By default, the constraint function receives a L
608             object as its first argument, and the value to be validated as the second. To
609             validate a field based on more inputs than just the field itself, see
610             L.
611              
612             B:
613              
614             # Notice the use of 'pop'--
615             # the object is the first arg passed to the method
616             # while the value is the second, and last arg.
617             my_zipcode_field => sub { my $val = pop; return $val =~ '/^\d{5}$/' },
618              
619             # OR you can reference a subroutine, which should work like the one above
620             my_zipcode_field => \&my_validation_routine,
621              
622             # An example of setting the constraint name.
623             my_zipcode_field => sub {
624             my ($dfv, $val) = @_;
625             $dfv->set_current_constraint_name('my_constraint_name');
626             return $val =~ '/^\d{5}$/'
627             },
628              
629             =item o
630              
631             an array reference
632              
633             An array reference is used to apply multiple constraints to a single
634             field. Any of the above options are valid entries the array.
635             See L below.
636              
637             For more details see L.
638              
639             =back
640              
641             =head2 constraint_method_regexp_map
642              
643             use Data::FormValidator::Constraints qw(:closures);
644              
645             # In your profile.
646             constraint_method_regexp_map => {
647             # All fields that end in _postcode have the 'postcode' constraint applied.
648             qr/_postcode$/ => postcode(),
649             },
650              
651             A hash ref where the keys are the regular expressions to
652             use and the values are the constraints to apply.
653              
654             If one or more constraints have already been defined for a given field using
655             C, C will add an additional
656             constraint for that field for each regular expression that matches.
657              
658             =head2 untaint_all_constraints
659              
660             untaint_all_constraints => 1,
661              
662             If this field is set, all form data that passes a constraint will be untainted.
663             The untainted data will be returned in the valid hash. Untainting is based on
664             the pattern match used by the constraint. Note that some constraint routines
665             may not provide untainting.
666              
667             See L for more information.
668              
669             This is overridden by C and C.
670              
671             =head2 untaint_constraint_fields
672              
673             untaint_constraint_fields => [qw(zipcode state)],
674              
675             Specifies that one or more fields will be untainted if they pass their
676             constraint(s). This can be set to a single field name or an array reference of
677             field names. The untainted data will be returned in the valid hash.
678              
679             This overrides the untaint_all_constraints flag.
680              
681             =head2 untaint_regexp_map
682              
683             untaint_regexp_map => [qr/some_field_\d/],
684              
685             Specifies that certain fields will be untainted if they pass their constraints
686             and match one of the regular expressions supplied. This can be set to a single
687             regex, or an array reference of regexes. The untainted data will be returned
688             in the valid hash.
689              
690             The above example would untaint the fields named C, and C
691             but not C.
692              
693             This overrides the untaint_all_constraints flag.
694              
695             =head2 missing_optional_valid
696              
697             missing_optional_valid => 1
698              
699             This can be set to a true value to cause optional fields with empty values to
700             be included in the valid hash. By default they are not included-- this is the
701             historical behavior.
702              
703             This is an important flag if you are using the contents of an "update" form to
704             update a record in a database. Without using the option, fields that have been
705             set back to "blank" may fail to get updated.
706              
707             =head2 validator_packages
708              
709             # load all the constraints and filters from these modules
710             validator_packages => [qw(Data::FormValidator::Constraints::Upload)],
711              
712             This key is used to define other packages which contain constraint routines or
713             filters. Set this key to a single package name, or an arrayref of several. All
714             of its constraint and filter routines beginning with 'match_', 'valid_' and
715             'filter_' will be imported into Data::FormValidator. This lets you reference
716             them in a constraint with just their name, just like built-in routines. You
717             can even override the provided validators.
718              
719             See L
720             documentation for more information
721              
722             =head2 msgs
723              
724             This key is used to define parameters related to formatting error messages
725             returned to the user.
726              
727             By default, invalid fields have the message "Invalid" associated with them
728             while missing fields have the message "Missing" associated with them.
729              
730             In the simplest case, nothing needs to be defined here, and the default values
731             will be used.
732              
733             The default formatting applied is designed for display in an XHTML web page.
734             That formatting is as followings:
735              
736             * %s
737              
738             The C<%s> will be replaced with the message. The effect is that the message
739             will appear in bold red with an asterisk before it. This style can be overridden by simply
740             defining "dfv_errors" appropriately in a style sheet, or by providing a new format string.
741              
742             Here's a more complex example that shows how to provide your own default message strings, as well
743             as providing custom messages per field, and handling multiple constraints:
744              
745             msgs => {
746              
747             # set a custom error prefix, defaults to none
748             prefix=> 'error_',
749              
750             # Set your own "Missing" message, defaults to "Missing"
751             missing => 'Not Here!',
752              
753             # Default invalid message, default's to "Invalid"
754             invalid => 'Problematic!',
755              
756             # message separator for multiple messages
757             # Defaults to ' '
758             invalid_separator => '
',
759              
760             # formatting string, default given above.
761             format => 'ERROR: %s',
762              
763             # Error messages, keyed by constraint name
764             # Your constraints must be named to use this.
765             constraints => {
766             'date_and_time' => 'Not a valid time format',
767             # ...
768             },
769              
770             # This token will be included in the hash if there are
771             # any errors returned. This can be useful with templating
772             # systems like HTML::Template
773             # The 'prefix' setting does not apply here.
774             # defaults to undefined
775             any_errors => 'some_errors',
776             }
777              
778             The hash that's prepared can be retrieved through the C method
779             described in the L documentation.
780              
781             =head2 msgs - callback
782              
783             I
784             yet received the testing the rest of the API has.>
785              
786             If the built-in message generation doesn't suit you, it is also possible to
787             provide your own by specifying a code reference:
788              
789             msgs => \&my_msgs_callback
790              
791             This will be called as a L method. It may
792             receive as arguments an additional hash reference of control parameters,
793             corresponding to the key names usually used in the C area of the
794             profile. You can ignore this information if you'd like.
795              
796             If you have an alternative error message handler you'd like to share, stick in
797             the C name space and upload it to CPAN.
798              
799             =head2 debug
800              
801             This method is used to print details about what is going on to STDERR.
802              
803             Currently only level '1' is used. It provides information about which
804             fields matched constraint_regexp_map.
805              
806             =head2 A shortcut for array refs
807              
808             A number of parts of the input profile specification include array references
809             as their values. In any of these places, you can simply use a string if you
810             only need to specify one value. For example, instead of
811              
812             filters => [ 'trim' ]
813              
814             you can simply say
815              
816             filters => 'trim'
817              
818             =head2 A note on regular expression formats
819              
820             In addition to using the preferred method of defining regular expressions
821             using C, a deprecated style of defining them as strings is also supported.
822              
823             Preferred:
824              
825             qr/this is great/
826              
827             Deprecated, but supported
828              
829             'm/this still works/'
830              
831             =head1 VALIDATING INPUT BASED ON MULTIPLE FIELDS
832              
833             You can pass more than one value into a constraint routine. For that, the
834             value of the constraint should be a hash reference. If you are creating your
835             own routines, be sure to read the section labeled
836             L,
837             in the Data::FormValidator::Constraints documentation. It describes
838             a newer and more flexible syntax.
839              
840             Using the original syntax, one key should be named C and should
841             have a value set to the reference of the subroutine or the name of a built-in
842             validator. Another required key is C. The value of the C key
843             is a reference to an array of the other elements to use in the validation. If
844             the element is a scalar, it is assumed to be a field name. The field is known
845             to Data::FormValidator, the value will be filtered through any defined filters
846             before it is passed in. If the value is a reference, the reference is passed
847             directly to the routine. Don't forget to include the name of the field to
848             check in that list, if you are using this syntax.
849              
850             B:
851              
852             cc_no => {
853             constraint => "cc_number",
854             params => [ qw( cc_no cc_type ) ],
855             },
856              
857              
858             =head1 MULTIPLE CONSTRAINTS
859              
860             Multiple constraints can be applied to a single field by defining the value of
861             the constraint to be an array reference. Each of the values in this array can
862             be any of the constraint types defined above.
863              
864             When using multiple constraints it is important to return the name of the
865             constraint that failed so you can distinguish between them. To do that,
866             either use a named constraint, or use the hash ref method of defining a
867             constraint and include a C key with a value set to the name of your
868             constraint. Here's an example:
869              
870             my_zipcode_field => [
871             'zip',
872             {
873             constraint_method => '/^406/',
874             name => 'starts_with_406',
875             }
876             ],
877              
878             You can use an array reference with a single constraint in it if you just want
879             to have the name of your failed constraint returned in the above fashion.
880              
881             Read about the C function above to see how multiple constraints
882             are returned differently with that method.
883              
884             =cut
885              
886             sub load_profiles {
887 35     35 0 47 my $self = shift;
888              
889 35         128 my $file = $self->{profile_file};
890 35 100       85 return unless $file;
891              
892 3 100       50 die "No such file: $file\n" unless -f $file;
893 2 50       6 die "Can't read $file\n" unless -r _;
894              
895 2         5 my $mtime = (stat _)[9];
896 2 50 33     6 return if $self->{profiles} and $self->{profiles_mtime} <= $mtime;
897              
898 2         588 $self->{profiles} = do $file;
899             die "Input profiles didn't return a hash ref: $@\n"
900 2 100       14 unless ref $self->{profiles} eq "HASH";
901              
902 1         3 $self->{profiles_mtime} = $mtime;
903             }
904              
905              
906              
907             # check the profile syntax and die if we have an error
908             sub _check_profile_syntax {
909 135     135   177 my $profile = shift;
910              
911 135 50       298 (ref $profile eq 'HASH') or
912             die "Invalid input profile: needs to be a hash reference\n";
913              
914 135         710 my @invalid;
915              
916             # check top level keys
917             {
918 135         601 my @valid_profile_keys = (qw/
919             constraint_methods
920             constraint_method_regexp_map
921             constraint_regexp_map
922             constraints
923             defaults
924             defaults_regexp_map
925             dependencies
926             dependency_groups
927             field_filter_regexp_map
928             field_filters
929             filters
930             missing_optional_valid
931             msgs
932             optional
933             optional_regexp
934             require_some
935             required
936             required_regexp
937             untaint_all_constraints
938             validator_packages
939             untaint_constraint_fields
940             untaint_regexp_map
941             debug
942             /);
943              
944             # If any of the keys in the profile are not listed as
945             # valid keys here, we die with an error
946 135         385 for my $key (keys %$profile) {
947 618 100       1907 push @invalid, $key unless grep $key eq $_, @valid_profile_keys;
948             }
949              
950 135         222 local $" = ', ';
951 135 100       392 if (@invalid) {
952 2         18 die "Invalid input profile: keys not recognised [@invalid]\n";
953             }
954             }
955              
956             # Check that constraint_methods are always code refs or REs
957             {
958             # Cases:
959             # 1. constraint_methods => { field => func() }
960             # 2. constraint_methods => { field => [ func() ] }
961             # 3. constraint_method_regex_map => { qr/^field/ => func() }
962             # 4. constraint_method_regex_map => { qr/^field/ => [ func() ] }
963             # 5. constraint_methods => { field => { constraint_method => func() } }
964              
965             # Could be improved by also naming the associated key for the bad value.
966 135         171 for my $key (grep { $profile->{$_} } qw/constraint_methods constraint_method_regexp_map/) {
  133         179  
  266         468  
967 99         88 for my $val (map { _arrayify($_) } values %{ $profile->{$key} }) {
  68         162  
  99         176  
968 69 100 100     310 if (ref $val eq 'HASH' && !grep(ref $val->{constraint_method} eq $_, 'CODE','Regexp')) {
    100          
969 1         8 die "Value for constraint_method within hashref '$val->{constraint_method}' not a code reference or Regexp . Do you need func(), not 'func'?";
970             }
971             # Cases 1 through 4.
972             elsif (!grep(ref $val eq $_, 'HASH','CODE','Regexp')) {
973 2         18 die "Value for constraint_method '$val' not a code reference or Regexp . Do you need func(), not 'func'?";
974             }
975             # Case 5.
976             else {
977             # We're cool. Nothing to do.
978             }
979             }
980             }
981             }
982              
983             # Check constraint hash keys
984             {
985 133         119 my @valid_constraint_hash_keys = (qw/
  130         268  
986             constraint
987             constraint_method
988             name
989             params
990             /);
991              
992 66         128 my @constraint_hashrefs = grep { ref $_ eq 'HASH' } values %{ $profile->{constraints} }
  69         131  
993 130 100       305 if $profile->{constraints};
994 12         26 push @constraint_hashrefs, grep { ref $_ eq 'HASH' } values %{ $profile->{constraint_regexp_map} }
  44         65  
995 130 100       275 if $profile->{constraint_regexp_map};
996              
997 130         200 for my $href (@constraint_hashrefs) {
998 28         51 for my $key (keys %$href) {
999 56 100       133 push @invalid, $key unless grep $key eq $_, @valid_constraint_hash_keys;
1000             }
1001             }
1002              
1003 130 100       294 if (@invalid) {
1004 2         12 die "Invalid input profile: constraint hashref keys not recognised [@invalid]\n";
1005             }
1006             }
1007              
1008             # Check msgs keys
1009             {
1010 130         136 my @valid_msgs_hash_keys = (qw/
  128         163  
  128         316  
1011             prefix
1012             missing
1013             invalid
1014             invalid_separator
1015             invalid_seperator
1016             format
1017             constraints
1018             any_errors
1019             /);
1020 128 100       297 if (ref $profile->{msgs} eq 'HASH') {
1021 15         17 for my $key (keys %{ $profile->{msgs} }) {
  15         36  
1022 17 100       51 push @invalid, $key unless grep $key eq $_, @valid_msgs_hash_keys;
1023             }
1024             }
1025 128 100       320 if (@invalid) {
1026 1         8 die "Invalid input profile: msgs keys not recognized: [@invalid]\n";
1027             }
1028             }
1029              
1030             }
1031              
1032              
1033             1;
1034              
1035             __END__