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