source: rdnap/lib/Params/Validate.pm@ 306

Last change on this file since 306 was 203, checked in by Rick van der Zwet, 14 years ago

Little wrapper, as, the orginal one is gone.

File size: 21.9 KB
RevLine 
[203]1package Params::Validate;
2
3use strict;
4
5BEGIN {
6 use Exporter;
7 use vars qw( $VERSION @ISA @EXPORT @EXPORT_OK
8 %EXPORT_TAGS %OPTIONS $options $NO_VALIDATION );
9
10 @ISA = 'Exporter';
11
12 $VERSION = '0.95';
13
14 my %tags = (
15 types => [
16 qw( SCALAR ARRAYREF HASHREF CODEREF GLOB GLOBREF
17 SCALARREF HANDLE BOOLEAN UNDEF OBJECT )
18 ],
19 );
20
21 %EXPORT_TAGS = (
22 'all' => [
23 qw( validate validate_pos validation_options validate_with ),
24 map { @{ $tags{$_} } } keys %tags
25 ],
26 %tags,
27 );
28
29 @EXPORT_OK = ( @{ $EXPORT_TAGS{all} }, 'set_options' );
30 @EXPORT = qw( validate validate_pos );
31
32 $NO_VALIDATION = $ENV{PERL_NO_VALIDATION};
33
34 eval { require Params::ValidateXS; } unless $ENV{PV_TEST_PERL};
35
36 if ( $@ || $ENV{PV_TEST_PERL} ) {
37 require Params::ValidatePP;
38 }
39}
40
411;
42
43__END__
44
45=head1 NAME
46
47Params::Validate - Validate method/function parameters
48
49=head1 SYNOPSIS
50
51 use Params::Validate qw(:all);
52
53 # takes named params (hash or hashref)
54 sub foo
55 {
56 validate( @_, { foo => 1, # mandatory
57 bar => 0, # optional
58 }
59 );
60 }
61
62 # takes positional params
63 sub bar
64 {
65 # first two are mandatory, third is optional
66 validate_pos( @_, 1, 1, 0 );
67 }
68
69
70 sub foo2
71 {
72 validate( @_,
73 { foo =>
74 # specify a type
75 { type => ARRAYREF },
76
77 bar =>
78 # specify an interface
79 { can => [ 'print', 'flush', 'frobnicate' ] },
80
81 baz =>
82 { type => SCALAR, # a scalar ...
83 # ... that is a plain integer ...
84 regex => qr/^\d+$/,
85 callbacks =>
86 { # ... and smaller than 90
87 'less than 90' => sub { shift() < 90 },
88 },
89 }
90 }
91 );
92 }
93
94 sub with_defaults
95 {
96 my %p = validate( @_, { foo => 1, # required
97 # $p{bar} will be 99 if bar is not
98 # given. bar is now optional.
99 bar => { default => 99 } } );
100 }
101
102 sub pos_with_defaults
103 {
104 my @p = validate_pos( @_, 1, { default => 99 } );
105 }
106
107 sub sets_options_on_call
108 {
109 my %p = validate_with
110 ( params => \@_,
111 spec => { foo => { type SCALAR, default => 2 } },
112 normalize_keys => sub { $_[0] =~ s/^-//; lc $_[0] },
113 );
114 }
115
116=head1 DESCRIPTION
117
118The Params::Validate module allows you to validate method or function
119call parameters to an arbitrary level of specificity. At the simplest
120level, it is capable of validating the required parameters were given
121and that no unspecified additional parameters were passed in.
122
123It is also capable of determining that a parameter is of a specific
124type, that it is an object of a certain class hierarchy, that it
125possesses certain methods, or applying validation callbacks to
126arguments.
127
128=head2 EXPORT
129
130The module always exports the C<validate()> and C<validate_pos()>
131functions.
132
133It also has an additional function available for export,
134C<validate_with>, which can be used to validate any type of
135parameters, and set various options on a per-invocation basis.
136
137In addition, it can export the following constants, which are used as
138part of the type checking. These are C<SCALAR>, C<ARRAYREF>,
139C<HASHREF>, C<CODEREF>, C<GLOB>, C<GLOBREF>, and C<SCALARREF>,
140C<UNDEF>, C<OBJECT>, C<BOOLEAN>, and C<HANDLE>. These are explained
141in the section on L<Type Validation|Params::Validate/Type Validation>.
142
143The constants are available via the export tag C<:types>. There is
144also an C<:all> tag which includes all of the constants as well as the
145C<validation_options()> function.
146
147=head1 PARAMETER VALIDATION
148
149The validation mechanisms provided by this module can handle both
150named or positional parameters. For the most part, the same features
151are available for each. The biggest difference is the way that the
152validation specification is given to the relevant subroutine. The
153other difference is in the error messages produced when validation
154checks fail.
155
156When handling named parameters, the module will accept either a hash
157or a hash reference.
158
159Subroutines expecting named parameters should call the C<validate()>
160subroutine like this:
161
162 validate( @_, { parameter1 => validation spec,
163 parameter2 => validation spec,
164 ...
165 } );
166
167Subroutines expecting positional parameters should call the
168C<validate_pos()> subroutine like this:
169
170 validate_pos( @_, { validation spec }, { validation spec } );
171
172=head2 Mandatory/Optional Parameters
173
174If you just want to specify that some parameters are mandatory and
175others are optional, this can be done very simply.
176
177For a subroutine expecting named parameters, you would do this:
178
179 validate( @_, { foo => 1, bar => 1, baz => 0 } );
180
181This says that the "foo" and "bar" parameters are mandatory and that
182the "baz" parameter is optional. The presence of any other
183parameters will cause an error.
184
185For a subroutine expecting positional parameters, you would do this:
186
187 validate_pos( @_, 1, 1, 0, 0 );
188
189This says that you expect at least 2 and no more than 4 parameters.
190If you have a subroutine that has a minimum number of parameters but
191can take any maximum number, you can do this:
192
193 validate_pos( @_, 1, 1, (0) x (@_ - 2) );
194
195This will always be valid as long as at least two parameters are
196given. A similar construct could be used for the more complex
197validation parameters described further on.
198
199Please note that this:
200
201 validate_pos( @_, 1, 1, 0, 1, 1 );
202
203makes absolutely no sense, so don't do it. Any zeros must come at the
204end of the validation specification.
205
206In addition, if you specify that a parameter can have a default, then
207it is considered optional.
208
209=head2 Type Validation
210
211This module supports the following simple types, which can be
212L<exported as constants|/EXPORT>:
213
214=over 4
215
216=item * SCALAR
217
218A scalar which is not a reference, such as C<10> or C<'hello'>. A
219parameter that is undefined is B<not> treated as a scalar. If you
220want to allow undefined values, you will have to specify C<SCALAR |
221UNDEF>.
222
223=item * ARRAYREF
224
225An array reference such as C<[1, 2, 3]> or C<\@foo>.
226
227=item * HASHREF
228
229A hash reference such as C<< { a => 1, b => 2 } >> or C<\%bar>.
230
231=item * CODEREF
232
233A subroutine reference such as C<\&foo_sub> or C<sub { print "hello" }>.
234
235=item * GLOB
236
237This one is a bit tricky. A glob would be something like C<*FOO>, but
238not C<\*FOO>, which is a glob reference. It should be noted that this
239trick:
240
241 my $fh = do { local *FH; };
242
243makes C<$fh> a glob, not a glob reference. On the other hand, the
244return value from C<Symbol::gensym> is a glob reference. Either can
245be used as a file or directory handle.
246
247=item * GLOBREF
248
249A glob reference such as C<\*FOO>. See the L<GLOB|GLOB> entry above
250for more details.
251
252=item * SCALARREF
253
254A reference to a scalar such as C<\$x>.
255
256=item * UNDEF
257
258An undefined value
259
260=item * OBJECT
261
262A blessed reference.
263
264=item * BOOLEAN
265
266This is a special option, and is just a shortcut for C<UNDEF | SCALAR>.
267
268=item * HANDLE
269
270This option is also special, and is just a shortcut for C<GLOB |
271GLOBREF>. However, it seems likely that most people interested in
272either globs or glob references are likely to really be interested in
273whether the parameter in question could be a valid file or directory
274handle.
275
276=back
277
278To specify that a parameter must be of a given type when using named
279parameters, do this:
280
281 validate( @_, { foo => { type => SCALAR },
282 bar => { type => HASHREF } } );
283
284If a parameter can be of more than one type, just use the bitwise or
285(C<|>) operator to combine them.
286
287 validate( @_, { foo => { type => GLOB | GLOBREF } );
288
289For positional parameters, this can be specified as follows:
290
291 validate_pos( @_, { type => SCALAR | ARRAYREF }, { type => CODEREF } );
292
293=head2 Interface Validation
294
295To specify that a parameter is expected to have a certain set of
296methods, we can do the following:
297
298 validate( @_,
299 { foo =>
300 # just has to be able to ->bar
301 { can => 'bar' } } );
302
303 ... or ...
304
305 validate( @_,
306 { foo =>
307 # must be able to ->bar and ->print
308 { can => [ qw( bar print ) ] } } );
309
310=head2 Class Validation
311
312A word of warning. When constructing your external interfaces, it is
313probably better to specify what methods you expect an object to
314have rather than what class it should be of (or a child of). This
315will make your API much more flexible.
316
317With that said, if you want to validate that an incoming parameter
318belongs to a class (or child class) or classes, do:
319
320 validate( @_,
321 { foo =>
322 { isa => 'My::Frobnicator' } } );
323
324 ... or ...
325
326 validate( @_,
327 { foo =>
328 { isa => [ qw( My::Frobnicator IO::Handle ) ] } } );
329 # must be both, not either!
330
331=head2 Regex Validation
332
333If you want to specify that a given parameter must match a specific
334regular expression, this can be done with "regex" spec key. For
335example:
336
337
338 validate( @_,
339 { foo =>
340 { regex => qr/^\d+$/ } } );
341
342The value of the "regex" key may be either a string or a pre-compiled
343regex created via C<qr>.
344
345If the value being checked against a regex is undefined, the regex is
346explicitly checked against the empty string ('') instead, in order to
347avoid "Use of uninitialized value" warnings.
348
349The C<Regexp::Common> module on CPAN is an excellent source of regular
350expressions suitable for validating input.
351
352=head2 Callback Validation
353
354If none of the above are enough, it is possible to pass in one or more
355callbacks to validate the parameter. The callback will be given the
356B<value> of the parameter as its first argument. Its second argument
357will be all the parameters, as a reference to either a hash or array.
358Callbacks are specified as hash reference. The key is an id for the
359callback (used in error messages) and the value is a subroutine
360reference, such as:
361
362 validate( @_,
363 { foo =>
364 { callbacks =>
365 { 'smaller than a breadbox' => sub { shift() < $breadbox },
366 'green or blue' =>
367 sub { $_[0] eq 'green' || $_[0] eq 'blue' } } } );
368
369 validate( @_,
370 { foo =>
371 { callbacks =>
372 { 'bigger than baz' => sub { $_[0] > $_[1]->{baz} } } } } );
373
374=head2 Untainting
375
376If you want values untainted, set the "untaint" key in a spec hashref
377to a true value, like this:
378
379 my %p =
380 validate( @_, { foo =>
381 { type => SCALAR, untaint => 1 },
382 bar =>
383 { type => ARRAYREF } } );
384
385This will untaint the "foo" parameter if the parameters are valid.
386
387Note that untainting is only done if I<all parameters> are valid.
388Also, only the return values are untainted, not the original values
389passed into the validation function.
390
391Asking for untainting of a reference value will not do anything, as
392C<Params::Validate> will only attempt to untaint the reference itself.
393
394=head2 Mandatory/Optional Revisited
395
396If you want to specify something such as type or interface, plus the
397fact that a parameter can be optional, do this:
398
399 validate( @_, { foo =>
400 { type => SCALAR },
401 bar =>
402 { type => ARRAYREF, optional => 1 } } );
403
404or this for positional parameters:
405
406 validate_pos( @_, { type => SCALAR }, { type => ARRAYREF, optional => 1 } );
407
408By default, parameters are assumed to be mandatory unless specified as
409optional.
410
411=head2 Dependencies
412
413It also possible to specify that a given optional parameter depends on
414the presence of one or more other optional parameters.
415
416 validate( @_, { cc_number =>
417 { type => SCALAR, optional => 1,
418 depends => [ 'cc_expiration', 'cc_holder_name' ],
419 },
420 cc_expiration
421 { type => SCALAR, optional => 1 },
422 cc_holder_name
423 { type => SCALAR, optional => 1 },
424 } );
425
426In this case, "cc_number", "cc_expiration", and "cc_holder_name" are
427all optional. However, if "cc_number" is provided, then
428"cc_expiration" and "cc_holder_name" must be provided as well.
429
430This allows you to group together sets of parameters that all must be
431provided together.
432
433The C<validate_pos()> version of dependencies is slightly different,
434in that you can only depend on one other parameter. Also, if for
435example, the second parameter 2 depends on the fourth parameter, then
436it implies a dependency on the third parameter as well. This is
437because if the fourth parameter is required, then the user must also
438provide a third parameter so that there can be four parameters in
439total.
440
441C<Params::Validate> will die if you try to depend on a parameter not
442declared as part of your parameter specification.
443
444=head2 Specifying defaults
445
446If the C<validate()> or C<validate_pos()> functions are called in a
447list context, they will return an array or hash containing the
448original parameters plus defaults as indicated by the validation spec.
449
450If the function is not called in a list context, providing a default
451in the validation spec still indicates that the parameter is optional.
452
453The hash or array returned from the function will always be a copy of
454the original parameters, in order to leave C<@_> untouched for the
455calling function.
456
457Simple examples of defaults would be:
458
459 my %p = validate( @_, { foo => 1, bar => { default => 99 } } );
460
461 my @p = validate( @_, 1, { default => 99 } );
462
463In scalar context, a hash reference or array reference will be
464returned, as appropriate.
465
466=head1 USAGE NOTES
467
468=head2 Validation failure
469
470By default, when validation fails C<Params::Validate> calls
471C<Carp::confess()>. This can be overridden by setting the C<on_fail>
472option, which is described in the L<"GLOBAL" OPTIONS|"GLOBAL" OPTIONS>
473section.
474
475=head2 Method calls
476
477When using this module to validate the parameters passed to a method
478call, you will probably want to remove the class/object from the
479parameter list B<before> calling C<validate()> or C<validate_pos()>.
480If your method expects named parameters, then this is necessary for
481the C<validate()> function to actually work, otherwise C<@_> will not
482be useable as a hash, because it will first have your object (or
483class) B<followed> by a set of keys and values.
484
485Thus the idiomatic usage of C<validate()> in a method call will look
486something like this:
487
488 sub method
489 {
490 my $self = shift;
491
492 my %params = validate( @_, { foo => 1, bar => { type => ARRAYREF } } );
493 }
494
495=head1 "GLOBAL" OPTIONS
496
497Because the API for the C<validate()> and C<validate_pos()> functions
498does not make it possible to specify any options other than the the
499validation spec, it is possible to set some options as
500pseudo-'globals'. These allow you to specify such things as whether
501or not the validation of named parameters should be case sensitive,
502for one example.
503
504These options are called pseudo-'globals' because these settings are
505B<only applied to calls originating from the package that set the
506options>.
507
508In other words, if I am in package C<Foo> and I call
509C<validation_options()>, those options are only in effect when I call
510C<validate()> from package C<Foo>.
511
512While this is quite different from how most other modules operate, I
513feel that this is necessary in able to make it possible for one
514module/application to use Params::Validate while still using other
515modules that also use Params::Validate, perhaps with different
516options set.
517
518The downside to this is that if you are writing an app with a standard
519calling style for all functions, and your app has ten modules, B<each
520module must include a call to C<validation_options()>>. You could of
521course write a module that all your modules use which uses various
522trickery to do this when imported.
523
524=head2 Options
525
526=over 4
527
528=item * normalize_keys => $callback
529
530This option is only relevant when dealing with named parameters.
531
532This callback will be used to transform the hash keys of both the
533parameters and the parameter spec when C<validate()> or
534C<validate_with()> are called.
535
536Any alterations made by this callback will be reflected in the
537parameter hash that is returned by the validation function. For
538example:
539
540 sub foo {
541 return
542 validate_with( params => \@_,
543 spec => { foo => { type => SCALAR } },
544 normalize_keys =>
545 sub { my $k = shift; $k =~ s/^-//; return uc $k },
546 );
547
548 }
549
550 %p = foo( foo => 20 );
551
552 # $p{FOO} is now 20
553
554 %p = foo( -fOo => 50 );
555
556 # $p{FOO} is now 50
557
558The callback must return a defined value.
559
560If a callback is given than the deprecated "ignore_case" and
561"strip_leading" options are ignored.
562
563=item * allow_extra => $boolean
564
565If true, then the validation routine will allow extra parameters not
566named in the validation specification. In the case of positional
567parameters, this allows an unlimited number of maximum parameters
568(though a minimum may still be set). Defaults to false.
569
570=item * on_fail => $callback
571
572If given, this callback will be called whenever a validation check
573fails. It will be called with a single parameter, which will be a
574string describing the failure. This is useful if you wish to have
575this module throw exceptions as objects rather than as strings, for
576example.
577
578This callback is expected to C<die()> internally. If it does not, the
579validation will proceed onwards, with unpredictable results.
580
581The default is to simply use the Carp module's C<confess()> function.
582
583=item * stack_skip => $number
584
585This tells Params::Validate how many stack frames to skip when finding
586a subroutine name to use in error messages. By default, it looks one
587frame back, at the immediate caller to C<validate()> or
588C<validate_pos()>. If this option is set, then the given number of
589frames are skipped instead.
590
591=item * ignore_case => $boolean
592
593DEPRECATED
594
595This is only relevant when dealing with named parameters. If it is
596true, then the validation code will ignore the case of parameter
597names. Defaults to false.
598
599=item * strip_leading => $characters
600
601DEPRECATED
602
603This too is only relevant when dealing with named parameters. If this
604is given then any parameters starting with these characters will be
605considered equivalent to parameters without them entirely. For
606example, if this is specified as '-', then C<-foo> and C<foo> would be
607considered identical.
608
609=back
610
611=head1 PER-INVOCATION OPTIONS
612
613The C<validate_with()> function can be used to set the options listed
614above on a per-invocation basis. For example:
615
616 my %p =
617 validate_with
618 ( params => \@_,
619 spec => { foo => { type => SCALAR },
620 bar => { default => 10 } },
621 allow_extra => 1,
622 );
623
624In addition to the options listed above, it is also possible to set
625the option "called", which should be a string. This string will be
626used in any error messages caused by a failure to meet the validation
627spec.
628
629This subroutine will validate named parameters as a hash if the "spec"
630parameter is a hash reference. If it is an array reference, the
631parameters are assumed to be positional.
632
633 my %p =
634 validate_with
635 ( params => \@_,
636 spec => { foo => { type => SCALAR },
637 bar => { default => 10 } },
638 allow_extra => 1,
639 called => 'The Quux::Baz class constructor',
640 );
641
642 my @p =
643 validate_with
644 ( params => \@_,
645 spec => [ { type => SCALAR },
646 { default => 10 } ],
647 allow_extra => 1,
648 called => 'The Quux::Baz class constructor',
649 );
650
651=head1 DISABLING VALIDATION
652
653If the environment variable C<PERL_NO_VALIDATION> is set to something
654true, then validation is turned off. This may be useful if you only
655want to use this module during development but don't want the speed
656hit during production.
657
658The only error that will be caught will be when an odd number of
659parameters are passed into a function/method that expects a hash.
660
661If you want to selectively turn validation on and off at runtime, you
662can directly set the C<$Params::Validate::NO_VALIDATION> global
663variable. It is B<strongly> recommended that you B<localize> any
664changes to this variable, because other modules you are using may
665expect validation to be on when they execute. For example:
666
667
668 {
669 local $Params::Validate::NO_VALIDATION = 1;
670 # no error
671 foo( bar => 2 );
672 }
673
674 # error
675 foo( bar => 2 );
676
677 sub foo
678 {
679 my %p = validate( @_, { foo => 1 } );
680 ...
681 }
682
683But if you want to shoot yourself in the foot and just turn it off, go
684ahead!
685
686=head1 LIMITATIONS
687
688Right now there is no way (short of a callback) to specify that
689something must be of one of a list of classes, or that it must possess
690one of a list of methods. If this is desired, it can be added in the
691future.
692
693Ideally, there would be only one validation function. If someone
694figures out how to do this, please let me know.
695
696=head1 SUPPORT
697
698Please submit bugs and patches to the CPAN RT system at
699http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Params%3A%3AValidate or
700via email at bug-params-validate@rt.cpan.org.
701
702Support questions can be sent to Dave at autarch@urth.org.
703
704The code repository is at https://svn.urth.org/svn/Params-Validate/
705
706=head1 DONATIONS
707
708If you'd like to thank me for the work I've done on this module,
709please consider making a "donation" to me via PayPal. I spend a lot of
710free time creating free software, and would appreciate any support
711you'd care to offer.
712
713Please note that B<I am not suggesting that you must do this> in order
714for me to continue working on this particular software. I will
715continue to do so, inasmuch as I have in the past, for as long as it
716interests me.
717
718Similarly, a donation made in this way will probably not make me work
719on this software much more, unless I get so many donations that I can
720consider working on free software full time, which seems unlikely at
721best.
722
723To donate, log into PayPal and send money to autarch@urth.org or use
724the button on this page:
725L<http://www.urth.org/~autarch/fs-donation.html>
726
727=head1 AUTHORS
728
729Dave Rolsky, <autarch@urth.org> and Ilya Martynov <ilya@martynov.org>
730
731=head1 COPYRIGHT
732
733Copyright (c) 2004-2007 David Rolsky. All rights reserved. This
734program is free software; you can redistribute it and/or modify it
735under the same terms as Perl itself.
736
737=cut
Note: See TracBrowser for help on using the repository browser.