1 package Params::Validate;
7 use vars qw( $VERSION @ISA @EXPORT @EXPORT_OK
8 %EXPORT_TAGS %OPTIONS $options $NO_VALIDATION );
16 qw( SCALAR ARRAYREF HASHREF CODEREF GLOB GLOBREF
17 SCALARREF HANDLE BOOLEAN UNDEF OBJECT )
23 qw( validate validate_pos validation_options validate_with ),
24 map { @{ $tags{$_} } } keys %tags
29 @EXPORT_OK = ( @{ $EXPORT_TAGS{all} }, 'set_options' );
30 @EXPORT = qw( validate validate_pos );
32 $NO_VALIDATION = $ENV{PERL_NO_VALIDATION};
34 eval { require Params::ValidateXS; } unless $ENV{PV_TEST_PERL};
36 if ( $@ || $ENV{PV_TEST_PERL} ) {
37 require Params::ValidatePP;
47 Params::Validate - Validate method/function parameters
51 use Params::Validate qw(:all);
53 # takes named params (hash or hashref)
56 validate( @_, { foo => 1, # mandatory
62 # takes positional params
65 # first two are mandatory, third is optional
66 validate_pos( @_, 1, 1, 0 );
78 # specify an interface
79 { can => [ 'print', 'flush', 'frobnicate' ] },
82 { type => SCALAR, # a scalar ...
83 # ... that is a plain integer ...
86 { # ... and smaller than 90
87 'less than 90' => sub { shift() < 90 },
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 } } );
102 sub pos_with_defaults
104 my @p = validate_pos( @_, 1, { default => 99 } );
107 sub sets_options_on_call
109 my %p = validate_with
111 spec => { foo => { type SCALAR, default => 2 } },
112 normalize_keys => sub { $_[0] =~ s/^-//; lc $_[0] },
118 The Params::Validate module allows you to validate method or function
119 call parameters to an arbitrary level of specificity. At the simplest
120 level, it is capable of validating the required parameters were given
121 and that no unspecified additional parameters were passed in.
123 It is also capable of determining that a parameter is of a specific
124 type, that it is an object of a certain class hierarchy, that it
125 possesses certain methods, or applying validation callbacks to
130 The module always exports the C<validate()> and C<validate_pos()>
133 It also has an additional function available for export,
134 C<validate_with>, which can be used to validate any type of
135 parameters, and set various options on a per-invocation basis.
137 In addition, it can export the following constants, which are used as
138 part of the type checking. These are C<SCALAR>, C<ARRAYREF>,
139 C<HASHREF>, C<CODEREF>, C<GLOB>, C<GLOBREF>, and C<SCALARREF>,
140 C<UNDEF>, C<OBJECT>, C<BOOLEAN>, and C<HANDLE>. These are explained
141 in the section on L<Type Validation|Params::Validate/Type Validation>.
143 The constants are available via the export tag C<:types>. There is
144 also an C<:all> tag which includes all of the constants as well as the
145 C<validation_options()> function.
147 =head1 PARAMETER VALIDATION
149 The validation mechanisms provided by this module can handle both
150 named or positional parameters. For the most part, the same features
151 are available for each. The biggest difference is the way that the
152 validation specification is given to the relevant subroutine. The
153 other difference is in the error messages produced when validation
156 When handling named parameters, the module will accept either a hash
159 Subroutines expecting named parameters should call the C<validate()>
160 subroutine like this:
162 validate( @_, { parameter1 => validation spec,
163 parameter2 => validation spec,
167 Subroutines expecting positional parameters should call the
168 C<validate_pos()> subroutine like this:
170 validate_pos( @_, { validation spec }, { validation spec } );
172 =head2 Mandatory/Optional Parameters
174 If you just want to specify that some parameters are mandatory and
175 others are optional, this can be done very simply.
177 For a subroutine expecting named parameters, you would do this:
179 validate( @_, { foo => 1, bar => 1, baz => 0 } );
181 This says that the "foo" and "bar" parameters are mandatory and that
182 the "baz" parameter is optional. The presence of any other
183 parameters will cause an error.
185 For a subroutine expecting positional parameters, you would do this:
187 validate_pos( @_, 1, 1, 0, 0 );
189 This says that you expect at least 2 and no more than 4 parameters.
190 If you have a subroutine that has a minimum number of parameters but
191 can take any maximum number, you can do this:
193 validate_pos( @_, 1, 1, (0) x (@_ - 2) );
195 This will always be valid as long as at least two parameters are
196 given. A similar construct could be used for the more complex
197 validation parameters described further on.
199 Please note that this:
201 validate_pos( @_, 1, 1, 0, 1, 1 );
203 makes absolutely no sense, so don't do it. Any zeros must come at the
204 end of the validation specification.
206 In addition, if you specify that a parameter can have a default, then
207 it is considered optional.
209 =head2 Type Validation
211 This module supports the following simple types, which can be
212 L<exported as constants|/EXPORT>:
218 A scalar which is not a reference, such as C<10> or C<'hello'>. A
219 parameter that is undefined is B<not> treated as a scalar. If you
220 want to allow undefined values, you will have to specify C<SCALAR |
225 An array reference such as C<[1, 2, 3]> or C<\@foo>.
229 A hash reference such as C<< { a => 1, b => 2 } >> or C<\%bar>.
233 A subroutine reference such as C<\&foo_sub> or C<sub { print "hello" }>.
237 This one is a bit tricky. A glob would be something like C<*FOO>, but
238 not C<\*FOO>, which is a glob reference. It should be noted that this
241 my $fh = do { local *FH; };
243 makes C<$fh> a glob, not a glob reference. On the other hand, the
244 return value from C<Symbol::gensym> is a glob reference. Either can
245 be used as a file or directory handle.
249 A glob reference such as C<\*FOO>. See the L<GLOB|GLOB> entry above
254 A reference to a scalar such as C<\$x>.
266 This is a special option, and is just a shortcut for C<UNDEF | SCALAR>.
270 This option is also special, and is just a shortcut for C<GLOB |
271 GLOBREF>. However, it seems likely that most people interested in
272 either globs or glob references are likely to really be interested in
273 whether the parameter in question could be a valid file or directory
278 To specify that a parameter must be of a given type when using named
281 validate( @_, { foo => { type => SCALAR },
282 bar => { type => HASHREF } } );
284 If a parameter can be of more than one type, just use the bitwise or
285 (C<|>) operator to combine them.
287 validate( @_, { foo => { type => GLOB | GLOBREF } );
289 For positional parameters, this can be specified as follows:
291 validate_pos( @_, { type => SCALAR | ARRAYREF }, { type => CODEREF } );
293 =head2 Interface Validation
295 To specify that a parameter is expected to have a certain set of
296 methods, we can do the following:
300 # just has to be able to ->bar
301 { can => 'bar' } } );
307 # must be able to ->bar and ->print
308 { can => [ qw( bar print ) ] } } );
310 =head2 Class Validation
312 A word of warning. When constructing your external interfaces, it is
313 probably better to specify what methods you expect an object to
314 have rather than what class it should be of (or a child of). This
315 will make your API much more flexible.
317 With that said, if you want to validate that an incoming parameter
318 belongs to a class (or child class) or classes, do:
322 { isa => 'My::Frobnicator' } } );
328 { isa => [ qw( My::Frobnicator IO::Handle ) ] } } );
329 # must be both, not either!
331 =head2 Regex Validation
333 If you want to specify that a given parameter must match a specific
334 regular expression, this can be done with "regex" spec key. For
340 { regex => qr/^\d+$/ } } );
342 The value of the "regex" key may be either a string or a pre-compiled
343 regex created via C<qr>.
345 If the value being checked against a regex is undefined, the regex is
346 explicitly checked against the empty string ('') instead, in order to
347 avoid "Use of uninitialized value" warnings.
349 The C<Regexp::Common> module on CPAN is an excellent source of regular
350 expressions suitable for validating input.
352 =head2 Callback Validation
354 If none of the above are enough, it is possible to pass in one or more
355 callbacks to validate the parameter. The callback will be given the
356 B<value> of the parameter as its first argument. Its second argument
357 will be all the parameters, as a reference to either a hash or array.
358 Callbacks are specified as hash reference. The key is an id for the
359 callback (used in error messages) and the value is a subroutine
365 { 'smaller than a breadbox' => sub { shift() < $breadbox },
367 sub { $_[0] eq 'green' || $_[0] eq 'blue' } } } );
372 { 'bigger than baz' => sub { $_[0] > $_[1]->{baz} } } } } );
376 If you want values untainted, set the "untaint" key in a spec hashref
377 to a true value, like this:
380 validate( @_, { foo =>
381 { type => SCALAR, untaint => 1 },
383 { type => ARRAYREF } } );
385 This will untaint the "foo" parameter if the parameters are valid.
387 Note that untainting is only done if I<all parameters> are valid.
388 Also, only the return values are untainted, not the original values
389 passed into the validation function.
391 Asking for untainting of a reference value will not do anything, as
392 C<Params::Validate> will only attempt to untaint the reference itself.
394 =head2 Mandatory/Optional Revisited
396 If you want to specify something such as type or interface, plus the
397 fact that a parameter can be optional, do this:
399 validate( @_, { foo =>
402 { type => ARRAYREF, optional => 1 } } );
404 or this for positional parameters:
406 validate_pos( @_, { type => SCALAR }, { type => ARRAYREF, optional => 1 } );
408 By default, parameters are assumed to be mandatory unless specified as
413 It also possible to specify that a given optional parameter depends on
414 the presence of one or more other optional parameters.
416 validate( @_, { cc_number =>
417 { type => SCALAR, optional => 1,
418 depends => [ 'cc_expiration', 'cc_holder_name' ],
421 { type => SCALAR, optional => 1 },
423 { type => SCALAR, optional => 1 },
426 In this case, "cc_number", "cc_expiration", and "cc_holder_name" are
427 all optional. However, if "cc_number" is provided, then
428 "cc_expiration" and "cc_holder_name" must be provided as well.
430 This allows you to group together sets of parameters that all must be
433 The C<validate_pos()> version of dependencies is slightly different,
434 in that you can only depend on one other parameter. Also, if for
435 example, the second parameter 2 depends on the fourth parameter, then
436 it implies a dependency on the third parameter as well. This is
437 because if the fourth parameter is required, then the user must also
438 provide a third parameter so that there can be four parameters in
441 C<Params::Validate> will die if you try to depend on a parameter not
442 declared as part of your parameter specification.
444 =head2 Specifying defaults
446 If the C<validate()> or C<validate_pos()> functions are called in a
447 list context, they will return an array or hash containing the
448 original parameters plus defaults as indicated by the validation spec.
450 If the function is not called in a list context, providing a default
451 in the validation spec still indicates that the parameter is optional.
453 The hash or array returned from the function will always be a copy of
454 the original parameters, in order to leave C<@_> untouched for the
457 Simple examples of defaults would be:
459 my %p = validate( @_, { foo => 1, bar => { default => 99 } } );
461 my @p = validate( @_, 1, { default => 99 } );
463 In scalar context, a hash reference or array reference will be
464 returned, as appropriate.
468 =head2 Validation failure
470 By default, when validation fails C<Params::Validate> calls
471 C<Carp::confess()>. This can be overridden by setting the C<on_fail>
472 option, which is described in the L<"GLOBAL" OPTIONS|"GLOBAL" OPTIONS>
477 When using this module to validate the parameters passed to a method
478 call, you will probably want to remove the class/object from the
479 parameter list B<before> calling C<validate()> or C<validate_pos()>.
480 If your method expects named parameters, then this is necessary for
481 the C<validate()> function to actually work, otherwise C<@_> will not
482 be useable as a hash, because it will first have your object (or
483 class) B<followed> by a set of keys and values.
485 Thus the idiomatic usage of C<validate()> in a method call will look
492 my %params = validate( @_, { foo => 1, bar => { type => ARRAYREF } } );
495 =head1 "GLOBAL" OPTIONS
497 Because the API for the C<validate()> and C<validate_pos()> functions
498 does not make it possible to specify any options other than the the
499 validation spec, it is possible to set some options as
500 pseudo-'globals'. These allow you to specify such things as whether
501 or not the validation of named parameters should be case sensitive,
504 These options are called pseudo-'globals' because these settings are
505 B<only applied to calls originating from the package that set the
508 In other words, if I am in package C<Foo> and I call
509 C<validation_options()>, those options are only in effect when I call
510 C<validate()> from package C<Foo>.
512 While this is quite different from how most other modules operate, I
513 feel that this is necessary in able to make it possible for one
514 module/application to use Params::Validate while still using other
515 modules that also use Params::Validate, perhaps with different
518 The downside to this is that if you are writing an app with a standard
519 calling style for all functions, and your app has ten modules, B<each
520 module must include a call to C<validation_options()>>. You could of
521 course write a module that all your modules use which uses various
522 trickery to do this when imported.
528 =item * normalize_keys => $callback
530 This option is only relevant when dealing with named parameters.
532 This callback will be used to transform the hash keys of both the
533 parameters and the parameter spec when C<validate()> or
534 C<validate_with()> are called.
536 Any alterations made by this callback will be reflected in the
537 parameter hash that is returned by the validation function. For
542 validate_with( params => \@_,
543 spec => { foo => { type => SCALAR } },
545 sub { my $k = shift; $k =~ s/^-//; return uc $k },
550 %p = foo( foo => 20 );
554 %p = foo( -fOo => 50 );
558 The callback must return a defined value.
560 If a callback is given than the deprecated "ignore_case" and
561 "strip_leading" options are ignored.
563 =item * allow_extra => $boolean
565 If true, then the validation routine will allow extra parameters not
566 named in the validation specification. In the case of positional
567 parameters, this allows an unlimited number of maximum parameters
568 (though a minimum may still be set). Defaults to false.
570 =item * on_fail => $callback
572 If given, this callback will be called whenever a validation check
573 fails. It will be called with a single parameter, which will be a
574 string describing the failure. This is useful if you wish to have
575 this module throw exceptions as objects rather than as strings, for
578 This callback is expected to C<die()> internally. If it does not, the
579 validation will proceed onwards, with unpredictable results.
581 The default is to simply use the Carp module's C<confess()> function.
583 =item * stack_skip => $number
585 This tells Params::Validate how many stack frames to skip when finding
586 a subroutine name to use in error messages. By default, it looks one
587 frame back, at the immediate caller to C<validate()> or
588 C<validate_pos()>. If this option is set, then the given number of
589 frames are skipped instead.
591 =item * ignore_case => $boolean
595 This is only relevant when dealing with named parameters. If it is
596 true, then the validation code will ignore the case of parameter
597 names. Defaults to false.
599 =item * strip_leading => $characters
603 This too is only relevant when dealing with named parameters. If this
604 is given then any parameters starting with these characters will be
605 considered equivalent to parameters without them entirely. For
606 example, if this is specified as '-', then C<-foo> and C<foo> would be
607 considered identical.
611 =head1 PER-INVOCATION OPTIONS
613 The C<validate_with()> function can be used to set the options listed
614 above on a per-invocation basis. For example:
619 spec => { foo => { type => SCALAR },
620 bar => { default => 10 } },
624 In addition to the options listed above, it is also possible to set
625 the option "called", which should be a string. This string will be
626 used in any error messages caused by a failure to meet the validation
629 This subroutine will validate named parameters as a hash if the "spec"
630 parameter is a hash reference. If it is an array reference, the
631 parameters are assumed to be positional.
636 spec => { foo => { type => SCALAR },
637 bar => { default => 10 } },
639 called => 'The Quux::Baz class constructor',
645 spec => [ { type => SCALAR },
648 called => 'The Quux::Baz class constructor',
651 =head1 DISABLING VALIDATION
653 If the environment variable C<PERL_NO_VALIDATION> is set to something
654 true, then validation is turned off. This may be useful if you only
655 want to use this module during development but don't want the speed
656 hit during production.
658 The only error that will be caught will be when an odd number of
659 parameters are passed into a function/method that expects a hash.
661 If you want to selectively turn validation on and off at runtime, you
662 can directly set the C<$Params::Validate::NO_VALIDATION> global
663 variable. It is B<strongly> recommended that you B<localize> any
664 changes to this variable, because other modules you are using may
665 expect validation to be on when they execute. For example:
669 local $Params::Validate::NO_VALIDATION = 1;
679 my %p = validate( @_, { foo => 1 } );
683 But if you want to shoot yourself in the foot and just turn it off, go
688 Right now there is no way (short of a callback) to specify that
689 something must be of one of a list of classes, or that it must possess
690 one of a list of methods. If this is desired, it can be added in the
693 Ideally, there would be only one validation function. If someone
694 figures out how to do this, please let me know.
698 Please submit bugs and patches to the CPAN RT system at
699 http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Params%3A%3AValidate or
700 via email at bug-params-validate@rt.cpan.org.
702 Support questions can be sent to Dave at autarch@urth.org.
704 The code repository is at https://svn.urth.org/svn/Params-Validate/
708 If you'd like to thank me for the work I've done on this module,
709 please consider making a "donation" to me via PayPal. I spend a lot of
710 free time creating free software, and would appreciate any support
713 Please note that B<I am not suggesting that you must do this> in order
714 for me to continue working on this particular software. I will
715 continue to do so, inasmuch as I have in the past, for as long as it
718 Similarly, a donation made in this way will probably not make me work
719 on this software much more, unless I get so many donations that I can
720 consider working on free software full time, which seems unlikely at
723 To donate, log into PayPal and send money to autarch@urth.org or use
724 the button on this page:
725 L<http://www.urth.org/~autarch/fs-donation.html>
729 Dave Rolsky, <autarch@urth.org> and Ilya Martynov <ilya@martynov.org>
733 Copyright (c) 2004-2007 David Rolsky. All rights reserved. This
734 program is free software; you can redistribute it and/or modify it
735 under the same terms as Perl itself.