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