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