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