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