README
1SYNOPSIS
2
3 use Validation::Class::Simple::Streamer;
4
5 my $params = {username => 'admin', password => 's3cret'};
6 my $input = Validation::Class::Simple::Streamer->new(params => $params);
7
8 # check username parameter
9 $input->check('username')->required->between('5-255');
10 $input->filters([qw/trim strip/]);
11
12 # check password parameter
13 $input->check('password')->required->between('5-255')->min_symbols(1);
14 $input->filters([qw/trim strip/]);
15
16 # run validate
17 $input->validate or die $input->errors_to_string;
18
19DESCRIPTION
20
21 Validation::Class is a scalable data validation library with interfaces
22 for applications of all sizes. The most common usage of
23 Validation::Class is to transform class namespaces into data validation
24 domains where consistency and reuse are primary concerns.
25 Validation::Class provides an extensible framework for defining
26 reusable data validation rules. It ships with a complete set of
27 pre-defined validations and filters referred to as "directives".
28
29 The core feature-set consist of self-validating methods, validation
30 profiles, reusable validation rules and templates, pre and post input
31 filtering, class inheritance, automatic array handling, and
32 extensibility (e.g. overriding default error messages, creating custom
33 validators, creating custom input filters and much more).
34 Validation::Class promotes DRY (don't repeat yourself) code. The main
35 benefit in using Validation::Class is that the architecture is designed
36 to increase the consistency of data input handling. The following is a
37 more traditional usage of Validation::Class, using the DSL to construct
38 a validator class:
39
40 package MyApp::Person;
41
42 use Validation::Class;
43
44 # data validation template
45 mixin basic => {
46 required => 1,
47 max_length => 255,
48 filters => [qw/trim strip/]
49 };
50
51 # data validation rules for the username parameter
52 field username => {
53 mixin => 'basic',
54 min_length => 5
55 };
56
57 # data validation rules for the password parameter
58 field password => {
59 mixin => 'basic',
60 min_length => 5,
61 min_symbols => 1
62 };
63
64 package main;
65
66 my $person = MyApp::Person->new(username => 'admin', password => 'secr3t');
67
68 # validate rules on the person object
69 unless ($person->validates) {
70 # handle the failures
71 warn $person->errors_to_string;
72 }
73
74 1;
75
76QUICKSTART
77
78 If you are looking for a simple in-line data validation module built
79 using the same tenets and principles as Validation::Class, please
80 review Validation::Class::Simple or
81 Validation::Class::Simple::Streamer. If you are new to
82 Validation::Class, or would like more information on the underpinnings
83 of this library and how it views and approaches data validation, please
84 review Validation::Class::Whitepaper. Please review the "GUIDED-TOUR"
85 in Validation::Class::Cookbook for a detailed step-by-step look into
86 how Validation::Class works.
87
88UPGRADE
89
90 Validation::Class is stable, its feature-set is complete, and is
91 currently in maintenance-only mode, i.e. Validation::Class will only be
92 updated with minor enhancements and bug fixes. However, the lessons
93 learned will be incorporated into a compelete rewrite uploaded under
94 the namespace Validation::Interface. The Validation::Interface fork is
95 designed to have a much simpler API with less options and better
96 execution, focused on validating hierarchical data as its primarily
97 objective.
98
99 The adopt keyword (or adt) copies configuration and functionality from
100 other Validation::Class classes. The adopt keyword takes three
101 arguments, the name of the class to be introspected, and the
102 configuration type and name to be recreated. Basically, anything you
103 can configure using a Validation::Class keyword can be adopted into
104 other classes using this keyword with the exception of coderefs
105 registered using the build keyword. Please note! If you are adopting a
106 field declaration which has an associated mixin directive defined on
107 the target class, you must adopt the mixin explicitly if you wish it's
108 values to be interpolated.
109
110 package MyApp::Exployee;
111
112 use Validate::Class;
113 use MyApp::Person;
114
115 adopt MyApp::Person, mixin => 'basic';
116 adopt MyApp::Person, field => 'first_name';
117 adopt MyApp::Person, field => 'last_name';
118 adopt MyApp::Person, profile => 'has_fullname';
119
120 1;
121
122 The attribute keyword (or has) registers a class attribute, i.e. it
123 creates an accessor (getter and setter) on the class. Attribute
124 declaration is flexible and only requires an attribute name to be
125 configured. Additionally, the attribute keyword can takes two
126 arguments, the attribute's name and a scalar or coderef to be used as
127 it's default value.
128
129 package MyApp::Person;
130
131 use Validate::Class;
132
133 attribute 'first_name' => 'Peter';
134 attribute 'last_name' => 'Venkman';
135 attribute 'full_name' => sub {
136 join ', ', $_[0]->last_name, $_[0]->first_name
137 };
138
139 attribute 'email_address';
140
141 1;
142
143 The build keyword (or bld) registers a coderef to be run at
144 instantiation much in the same way the common BUILD routine is used in
145 modern OO frameworks.
146
147 package MyApp::Person;
148
149 use Validation::Class;
150
151 build sub {
152
153 my ($self, $args) = @_;
154
155 # run after instantiation in the order defined
156
157 };
158
159 1;
160
161 The build keyword takes one argument, a coderef which is passed the
162 instantiated class object.
163
164 The directive keyword (or dir) registers custom validator directives to
165 be used in your field definitions. Please note that custom directives
166 can only be used with field definitions. This is a means of extending
167 the list of directives per instance. See the list of core directives,
168 Validation::Class::Directives, or review Validation::Class::Directive
169 for insight into creating your own CPAN installable directives.
170
171 package MyApp::Person;
172
173 use Validate::Class;
174
175 # define a custom class-level directive
176 directive 'blacklisted' => sub {
177
178 my ($self, $field, $param) = @_;
179
180 if (defined $field->{blacklisted} && defined $param) {
181 if ($field->{required} || $param) {
182 if (exists_in_blacklist($field->{blacklisted}, $param)) {
183 my $handle = $field->label || $field->name;
184 $field->errors->add("$handle has been blacklisted");
185 return 0;
186 }
187 }
188 }
189
190 return 1;
191
192 };
193
194 field 'email_address' => {
195 blacklisted => '/path/to/blacklist'
196 email => 1,
197 };
198
199 1;
200
201 The directive keyword takes two arguments, the name of the directive
202 and a coderef which will be used to validate the associated field. The
203 coderef is passed four ordered parameters; a directive object, the
204 class prototype object, the current field object, and the matching
205 parameter's value. The validator (coderef) is evaluated by its return
206 value as well as whether it altered any error containers.
207
208 The document keyword (or doc) registers a data matching profile which
209 can be used to validate heiarchal data. It will store a hashref with
210 pre-define path matching rules for the data structures you wish to
211 validate. The "path matching rules", which use a specialized object
212 notation, referred to as the document notation, can be thought of as a
213 kind-of simplified regular expression which is executed against the
214 flattened data structure. The following are a few general use-cases:
215
216 package MyApp::Person;
217
218 use Validation::Class;
219
220 field 'string' => {
221 mixin => [':str']
222 };
223
224 # given this JSON data structure
225 {
226 "id": "1234-A",
227 "name": {
228 "first_name" : "Bob",
229 "last_name" : "Smith",
230 },
231 "title": "CIO",
232 "friends" : [],
233 }
234
235 # select id to validate against the string rule
236 document 'foobar' =>
237 { 'id' => 'string' };
238
239 # select name -> first_name/last_name to validate against the string rule
240 document 'foobar' =>
241 {'name.first_name' => 'string', 'name.last_name' => 'string'};
242
243 # or
244 document 'foobar' =>
245 {'name.*_name' => 'string'};
246
247 # select each element in friends to validate against the string rule
248 document 'foobar' =>
249 { 'friends.@' => 'string' };
250
251 # or select an element of a hashref in each element in friends to validate
252 # against the string rule
253 document 'foobar' =>
254 { 'friends.@.name' => 'string' };
255
256 The document declaration's keys should follow the aforementioned
257 document notation schema and it's values should be strings which
258 correspond to the names of fields (or other document declarations) that
259 will be used to preform the data validation. It is possible to combine
260 document declarations to validate hierarchical data that contains data
261 structures matching one or more document patterns. The following is an
262 example of what that might look like.
263
264 package MyApp::Person;
265
266 use Validation::Class;
267
268 # data validation rule
269 field 'name' => {
270 mixin => [':str'],
271 pattern => qr/^[A-Za-z ]+$/,
272 max_length => 20,
273 };
274
275 # data validation map / document notation schema
276 document 'friend' => {
277 'name' => 'name'
278 };
279
280 # data validation map / document notation schema
281 document 'person' => {
282 'name' => 'name',
283 'friends.@' => 'friend'
284 };
285
286 package main;
287
288 my $data = {
289 "name" => "Anita Campbell-Green",
290 "friends" => [
291 { "name" => "Horace" },
292 { "name" => "Skinner" },
293 { "name" => "Alonzo" },
294 { "name" => "Frederick" },
295 ],
296 };
297
298 my $person = MyApp::Person->new;
299
300 unless ($person->validate_document(person => $data)) {
301 warn $person->errors_to_string if $person->error_count;
302 }
303
304 1;
305
306 Alternatively, the following is a more verbose data validation class
307 using traditional styling and configuration.
308
309 package MyApp::Person;
310
311 use Validation::Class;
312
313 field 'id' => {
314 mixin => [':str'],
315 filters => ['numeric'],
316 max_length => 2,
317 };
318
319 field 'name' => {
320 mixin => [':str'],
321 pattern => qr/^[A-Za-z ]+$/,
322 max_length => 20,
323 };
324
325 field 'rating' => {
326 mixin => [':str'],
327 pattern => qr/^\-?\d+$/,
328 };
329
330 field 'tag' => {
331 mixin => [':str'],
332 pattern => qr/^(?!evil)\w+/,
333 max_length => 20,
334 };
335
336 document 'person' => {
337 'id' => 'id',
338 'name' => 'name',
339 'company.name' => 'name',
340 'company.supervisor.name' => 'name',
341 'company.supervisor.rating.@.*' => 'rating',
342 'company.tags.@' => 'name'
343 };
344
345 package main;
346
347 my $data = {
348 "id" => "1234-ABC",
349 "name" => "Anita Campbell-Green",
350 "title" => "Designer",
351 "company" => {
352 "name" => "House of de Vil",
353 "supervisor" => {
354 "name" => "Cruella de Vil",
355 "rating" => [
356 { "support" => -9,
357 "guidance" => -9
358 }
359 ]
360 },
361 "tags" => [
362 "evil",
363 "cruelty",
364 "dogs"
365 ]
366 },
367 };
368
369 my $person = MyApp::Person->new;
370
371 unless ($person->validate_document(person => $data)) {
372 warn $person->errors_to_string if $person->error_count;
373 }
374
375 1;
376
377 Additionally, the following is yet another way to validate a document
378 by passing the document specification directly instead of by name.
379
380 package MyApp::Person;
381
382 use Validation::Class;
383
384 package main;
385
386 my $data = {
387 "id" => "1234-ABC",
388 "name" => "Anita Campbell-Green",
389 "title" => "Designer",
390 "company" => {
391 "name" => "House of de Vil",
392 "supervisor" => {
393 "name" => "Cruella de Vil",
394 "rating" => [
395 { "support" => -9,
396 "guidance" => -9
397 }
398 ]
399 },
400 "tags" => [
401 "evil",
402 "cruelty",
403 "dogs"
404 ]
405 },
406 };
407
408 my $spec = {
409 'id' => { max_length => 2 },
410 'name' => { mixin => ':str' },
411 'company.name' => { mixin => ':str' },
412 'company.supervisor.name' => { mixin => ':str' },
413 'company.supervisor.rating.@.*' => { pattern => qr/^(?!evil)\w+/ },
414 'company.tags.@' => { max_length => 20 },
415 };
416
417 my $person = MyApp::Person->new;
418
419 unless ($person->validate_document($spec => $data)) {
420 warn $person->errors_to_string if $person->error_count;
421 }
422
423 1;
424
425 The ensure keyword (or ens) is used to convert a pre-existing method
426 into an auto-validating method. The auto-validating method will be
427 registered and function as if it was created using the method keyword.
428 The original pre-existing method will be overridden with a modifed
429 version which performs the pre and/or post validation routines.
430
431 package MyApp::Person;
432
433 use Validation::Class;
434
435 sub register {
436 ...
437 }
438
439 ensure register => {
440 input => ['name', '+email', 'username', '+password', '+password2'],
441 output => ['+id'], # optional output validation, dies on failure
442 };
443
444 package main;
445
446 my $person = MyApp::Person->new(params => $params);
447
448 if ($person->register) {
449 # handle the successful registration
450 }
451
452 1;
453
454 The ensure keyword takes two arguments, the name of the method to be
455 overridden and a hashref of required key/value pairs. The hashref may
456 have an input key (e.g. input, input_document, input_profile, or
457 input_method). The `input` key (specifically) must have a value which
458 must be either an arrayref of fields to be validated, or a scalar value
459 which matches (a validation profile or auto-validating method name).
460 The hashref may also have an output key (e.g. output, output_document,
461 output_profile, or output_method). The `output` key (specifically) must
462 have a value which must be either an arrayref of fields to be
463 validated, or a scalar value which matches (a validation profile or
464 auto-validating method name). Whether and what the method returns is
465 yours to decide. The method will return undefined if validation fails.
466 The ensure keyword wraps and functions much in the same way as the
467 method keyword.
468
469 The field keyword (or fld) registers a data validation rule for reuse
470 and validation in code. The field name should correspond with the
471 parameter name expected to be passed to your validation class or
472 validated against.
473
474 package MyApp::Person;
475
476 use Validation::Class;
477
478 field 'username' => {
479 required => 1,
480 min_length => 1,
481 max_length => 255
482 };
483
484 The field keyword takes two arguments, the field name and a hashref of
485 key/values pairs known as directives. For more information on
486 pre-defined directives, please review the "list of core directives".
487
488 The field keyword also creates accessors which provide easy access to
489 the field's corresponding parameter value(s). Accessors will be created
490 using the field's name as a label having any special characters
491 replaced with an underscore.
492
493 # accessor will be created as send_reminders
494 field 'send-reminders' => {
495 length => 1
496 };
497
498 Please note that prefixing field names with a double plus-symbol
499 instructs the register to merge your declaration with any pre-existing
500 declarations within the same scope (e.g. fields imported via loading
501 roles), whereas prefixing field names with a single plus-symbol
502 instructs the register to overwrite any pre-existing declarations.
503
504 package MyApp::Person;
505
506 use Validation::Class;
507
508 set role => 'MyApp::User';
509
510 # append existing field and overwrite directives
511 field '++email_address' => {
512 required => 1
513 };
514
515 # redefine existing field
516 field '+login' => {
517 required => 1
518 };
519
520 1;
521
522 The filter keyword (or flt) registers custom filters to be used in your
523 field definitions. It is a means of extending the pre-existing filters
524 declared by the "filters directive" before instantiation.
525
526 package MyApp::Person;
527
528 use Validate::Class;
529
530 filter 'flatten' => sub {
531 $_[0] =~ s/[\t\r\n]+/ /g;
532 return $_[0];
533 };
534
535 field 'biography' => {
536 filters => ['trim', 'strip', 'flatten']
537 };
538
539 1;
540
541 The filter keyword takes two arguments, the name of the filter and a
542 coderef which will be used to filter the value the associated field.
543 The coderef is passed the value of the field and that value MUST be
544 operated on directly. The coderef should also return the transformed
545 value.
546
547 The load keyword (or set), which can also be used as a class method,
548 provides options for extending the current class by declaring roles,
549 requirements, etc.
550
551 The process of applying roles, requirement, and other settings to the
552 current class mainly involves introspecting the namespace's methods and
553 merging relevant parts of the prototype configuration.
554
555 The `classes` (or class) option uses Module::Find to load all child
556 classes (in-all-subdirectories) for convenient access through the
557 "class" in Validation::Class::Prototype method, and when introspecting
558 a larger application. This option accepts an arrayref or single
559 argument.
560
561 package MyApp;
562
563 use Validation::Class;
564
565 load classes => ['MyApp::Domain1', 'MyApp::Domain2'];
566
567 package main;
568
569 my $app = MyApp->new;
570
571 my $person = $app->class('person'); # return a new MyApp::Person object
572
573 1;
574
575 package MyApp::User;
576
577 use Validate::Class;
578
579 load requirements => 'activate';
580
581 package MyApp::Person;
582
583 use Validation::Class;
584
585 load role => 'MyApp::User';
586
587 sub activate {}
588
589 1;
590
591 The `requirements` (or required) option is used to ensure that if/when
592 the class is used as a role the calling class has specific pre-existing
593 methods. This option accepts an arrayref or single argument.
594
595 package MyApp::User;
596
597 use Validate::Class;
598
599 load requirements => ['activate', 'deactivate'];
600
601 1;
602
603 package MyApp::Person;
604
605 use Validation::Class;
606
607 load role => 'MyApp::User';
608
609 1;
610
611 The `roles` (or role) option is used to load and inherit functionality
612 from other validation classes. These classes should be used and
613 thought-of as roles although they can also be fully-functioning
614 validation classes. This option accepts an arrayref or single argument.
615
616 package MyApp::Person;
617
618 use Validation::Class;
619
620 load roles => ['MyApp::User', 'MyApp::Visitor'];
621
622 1;
623
624 The message keyword (or msg) registers a class-level error message
625 template that will be used in place of the error message defined in the
626 corresponding directive class if defined. Error messages can also be
627 overridden at the individual field-level as well. See the
628 Validation::Class::Directive::Messages for instructions on how to
629 override error messages at the field-level.
630
631 package MyApp::Person;
632
633 use Validation::Class;
634
635 field email_address => {
636 required => 1,
637 min_length => 3,
638 messages => {
639 # field-level error message override
640 min_length => '%s is not even close to being a valid email address'
641 }
642 };
643
644 # class-level error message overrides
645 message required => '%s is needed to proceed';
646 message min_length => '%s needs more characters';
647
648 1;
649
650 The message keyword takes two arguments, the name of the directive
651 whose error message you wish to override and a string which will be
652 used to as a template which is feed to sprintf to format the message.
653
654 The method keyword (or mth) is used to register an auto-validating
655 method. Similar to method signatures, an auto-validating method can
656 leverage pre-existing validation rules and profiles to ensure a method
657 has the required pre/post-conditions and data necessary for execution.
658
659 package MyApp::Person;
660
661 use Validation::Class;
662
663 method 'register' => {
664
665 input => ['name', '+email', 'username', '+password', '+password2'],
666 output => ['+id'], # optional output validation, dies on failure
667 using => sub {
668
669 my ($self, @args) = @_;
670
671 # do something registrationy
672 $self->id(...); # set the ID field for output validation
673
674 return $self;
675
676 }
677
678 };
679
680 package main;
681
682 my $person = MyApp::Person->new(params => $params);
683
684 if ($person->register) {
685
686 # handle the successful registration
687
688 }
689
690 1;
691
692 The method keyword takes two arguments, the name of the method to be
693 created and a hashref of required key/value pairs. The hashref may have
694 a `using` key whose value is the coderef to be executed upon successful
695 validation. The `using` key is only optional when a pre-existing
696 subroutine has the same name or the method being declared prefixed with
697 a dash or dash-process-dash. The following are valid subroutine names
698 to be called by the method declaration in absence of a `using` key.
699 Please note, unlike the ensure keyword, any pre-existing subroutines
700 will not be wrapped-and-replaced and can be executed without validation
701 if called directly.
702
703 sub _name {
704 ...
705 }
706
707 sub _process_name {
708 ...
709 }
710
711 The hashref may have an input key (e.g. input, input_document,
712 input_profile, or input_method). The `input` key (specifically) must
713 have a value which must be either an arrayref of fields to be
714 validated, or a scalar value which matches (a validation profile or
715 auto-validating method name), which will be used to perform data
716 validation before the aforementioned coderef has been executed. Whether
717 and what the method returns is yours to decide. The method will return
718 undefined if validation fails.
719
720 # alternate usage
721
722 method 'registration' => {
723 input => ['name', '+email', 'username', '+password', '+password2'],
724 output => ['+id'], # optional output validation, dies on failure
725 };
726
727 sub _process_registration {
728 my ($self, @args) = @_;
729 $self->id(...); # set the ID field for output validation
730 return $self;
731 }
732
733 Optionally the hashref may also have an output key (e.g. output,
734 output_document, output_profile, or output_method). The `output` key
735 (specifically) must have a value which must be either an arrayref of
736 fields to be validated, or a scalar value which matches (a validation
737 profile or auto-validating method name), which will be used to perform
738 data validation after the aforementioned coderef has been executed.
739
740 Please note that output validation failure will cause the program to
741 die, the premise behind this decision is based on the assumption that
742 given successfully validated input a routine's output should be
743 predictable and if an error occurs it is most-likely a program error as
744 opposed to a user error.
745
746 See the ignore_failure and report_failure attributes on the prototype
747 to control how method validation failures are handled.
748
749 The mixin keyword (or mxn) registers a validation rule template that
750 can be applied (or "mixed-in") to any field by specifying the mixin
751 directive. Mixin directives are processed first so existing field
752 directives will override any directives created by the mixin directive.
753
754 package MyApp::Person;
755
756 use Validation::Class;
757
758 mixin 'boilerplate' => {
759 required => 1,
760 min_length => 1,
761 max_length => 255
762 };
763
764 field 'username' => {
765 # min_length, max_length, .. required will be overridden
766 mixin => 'boilerplate',
767 required => 0
768 };
769
770 Since version 7.900015, all classes are automatically configured with
771 the following default mixins for the sake of convenience:
772
773 mixin ':flg' => {
774 required => 1,
775 min_length => 1,
776 filters => [qw/trim strip numeric/],
777 between => [0, 1]
778 };
779
780 mixin ':num' => {
781 required => 1,
782 min_length => 1,
783 filters => [qw/trim strip numeric/]
784 };
785
786 mixin ':str' => {
787 required => 1,
788 min_length => 1,
789 filters => [qw/trim strip/]
790 };
791
792 Please note that the aforementioned mixin names are prefixed with a
793 semi-colon but are treated as an exception to the rule. Prefixing mixin
794 names with a double plus-symbol instructs the register to merge your
795 declaration with any pre-existing declarations within the same scope
796 (e.g. mixins imported via loading roles), whereas prefixing mixin names
797 with a single plus-symbol instructs the register to overwrite any
798 pre-existing declarations.
799
800 package MyApp::Moderator;
801
802 use Validation::Class;
803
804 set role => 'MyApp::Person';
805
806 # overwrite and append existing mixin
807 mixin '++boilerplate' => {
808 min_symbols => 1
809 };
810
811 # redefine existing mixin
812 mixin '+username' => {
813 required => 1
814 };
815
816 1;
817
818 The mixin keyword takes two arguments, the mixin name and a hashref of
819 key/values pairs known as directives.
820
821 The new method instantiates a new class object, it performs a series of
822 actions (magic) required for the class to function properly, and for
823 that reason, this method should never be overridden. Use the build
824 keyword for hooking into the instantiation process.
825
826 In the event a foreign (pre-existing) `new` method is detected, an
827 `initialize_validator` method will be injected into the class
828 containing the code (magic) necessary to normalize your environment.
829
830 package MyApp::Person;
831
832 use Validation::Class;
833
834 # hook
835 build sub {
836
837 my ($self, @args) = @_; # on instantiation
838
839 };
840
841 sub new {
842
843 # rolled my own
844 my $self = bless {}, shift;
845
846 # execute magic
847 $self->initialize_validator;
848
849 }
850
851 1;
852
853 The profile keyword (or pro) registers a validation profile (coderef)
854 which as in the traditional use of the term is a sequence of validation
855 routines that validates data relevant to a specific action.
856
857 package MyApp::Person;
858
859 use Validation::Class;
860
861 profile 'check_email' => sub {
862
863 my ($self, @args) = @_;
864
865 if ($self->email_exists) {
866 my $email = $self->fields->get('email');
867 $email->errors->add('Email already exists');
868 return 0;
869 }
870
871 return 1;
872
873 };
874
875 package main;
876
877 my $user = MyApp::Person->new(params => $params);
878
879 unless ($user->validate_profile('check_email')) {
880 # handle failures
881 }
882
883 1;
884
885 The profile keyword takes two arguments, a profile name and coderef
886 which will be used to execute a sequence of actions for validation
887 purposes.
888
889 The prototype method (or proto) returns an instance of the associated
890 class prototype. The class prototype is responsible for manipulating
891 and validating the data model (the class). It is not likely that you'll
892 need to access this method directly, see Validation::Class::Prototype.
893
894 package MyApp::Person;
895
896 use Validation::Class;
897
898 package main;
899
900 my $person = MyApp::Person->new;
901
902 my $prototype = $person->prototype;
903
904 1;
905
906PROXY METHODS
907
908 Validation::Class mostly provides sugar functions for modeling your
909 data validation requirements. Each class you create is associated with
910 a prototype class which provides the data validation engine and keeps
911 your class namespace free from pollution, please see
912 Validation::Class::Prototype for more information on specific methods
913 and attributes. Validation::Class injects a few proxy methods into your
914 class which are basically aliases to the corresponding prototype class
915 methods, however it is possible to access the prototype directly using
916 the proto/prototype methods.
917
918 =proxy_method class
919
920 $self->class;
921
922 See "class" in Validation::Class::Prototype for full documentation.
923
924 =proxy_method clear_queue
925
926 $self->clear_queue;
927
928 See "clear_queue" in Validation::Class::Prototype for full
929 documentation.
930
931 =proxy_method error_count
932
933 $self->error_count;
934
935 See "error_count" in Validation::Class::Prototype for full
936 documentation.
937
938 =proxy_method error_fields
939
940 $self->error_fields;
941
942 See "error_fields" in Validation::Class::Prototype for full
943 documentation.
944
945 =proxy_method errors
946
947 $self->errors;
948
949 See "errors" in Validation::Class::Prototype for full documentation.
950
951 =proxy_method errors_to_string
952
953 $self->errors_to_string;
954
955 See "errors_to_string" in Validation::Class::Prototype for full
956 documentation.
957
958 =proxy_method get_errors
959
960 $self->get_errors;
961
962 See "get_errors" in Validation::Class::Prototype for full
963 documentation.
964
965 =proxy_method get_fields
966
967 $self->get_fields;
968
969 See "get_fields" in Validation::Class::Prototype for full
970 documentation.
971
972 =proxy_method get_hash
973
974 $self->get_hash;
975
976 See "get_hash" in Validation::Class::Prototype for full documentation.
977
978 =proxy_method get_params
979
980 $self->get_params;
981
982 See "get_params" in Validation::Class::Prototype for full
983 documentation.
984
985 =proxy_method get_values
986
987 $self->get_values;
988
989 See "get_values" in Validation::Class::Prototype for full
990 documentation.
991
992 =proxy_method fields
993
994 $self->fields;
995
996 See "fields" in Validation::Class::Prototype for full documentation.
997
998 =proxy_method filtering
999
1000 $self->filtering;
1001
1002 See "filtering" in Validation::Class::Prototype for full documentation.
1003
1004 =proxy_method ignore_failure
1005
1006 $self->ignore_failure;
1007
1008 See "ignore_failure" in Validation::Class::Prototype for full
1009 documentation.
1010
1011 =proxy_method ignore_intervention
1012
1013 $self->ignore_intervention;
1014
1015 See "ignore_intervention" in Validation::Class::Prototype for full
1016 documentation.
1017
1018 =proxy_method ignore_unknown
1019
1020 $self->ignore_unknown;
1021
1022 See "ignore_unknown" in Validation::Class::Prototype for full
1023 documentation.
1024
1025 =proxy_method is_valid
1026
1027 $self->is_valid;
1028
1029 See "is_valid" in Validation::Class::Prototype for full documentation.
1030
1031 =proxy_method param
1032
1033 $self->param;
1034
1035 See "param" in Validation::Class::Prototype for full documentation.
1036
1037 =proxy_method params
1038
1039 $self->params;
1040
1041 See "params" in Validation::Class::Prototype for full documentation.
1042
1043 =proxy_method plugin
1044
1045 $self->plugin;
1046
1047 See "plugin" in Validation::Class::Prototype for full documentation.
1048
1049 =proxy_method queue
1050
1051 $self->queue;
1052
1053 See "queue" in Validation::Class::Prototype for full documentation.
1054
1055 =proxy_method report_failure
1056
1057 $self->report_failure;
1058
1059 See "report_failure" in Validation::Class::Prototype for full
1060 documentation.
1061
1062 =proxy_method report_unknown
1063
1064 $self->report_unknown;
1065
1066 See "report_unknown" in Validation::Class::Prototype for full
1067 documentation.
1068
1069 =proxy_method reset_errors
1070
1071 $self->reset_errors;
1072
1073 See "reset_errors" in Validation::Class::Prototype for full
1074 documentation.
1075
1076 =proxy_method reset_fields
1077
1078 $self->reset_fields;
1079
1080 See "reset_fields" in Validation::Class::Prototype for full
1081 documentation.
1082
1083 =proxy_method reset_params
1084
1085 $self->reset_params;
1086
1087 See "reset_params" in Validation::Class::Prototype for full
1088 documentation.
1089
1090 =proxy_method set_errors
1091
1092 $self->set_errors;
1093
1094 See "set_errors" in Validation::Class::Prototype for full
1095 documentation.
1096
1097 =proxy_method set_fields
1098
1099 $self->set_fields;
1100
1101 See "set_fields" in Validation::Class::Prototype for full
1102 documentation.
1103
1104 =proxy_method set_params
1105
1106 $self->set_params;
1107
1108 See "set_params" in Validation::Class::Prototype for full
1109 documentation.
1110
1111 =proxy_method set_method
1112
1113 $self->set_method;
1114
1115 See "set_method" in Validation::Class::Prototype for full
1116 documentation.
1117
1118 =proxy_method stash
1119
1120 $self->stash;
1121
1122 See "stash" in Validation::Class::Prototype for full documentation.
1123
1124 =proxy_method validate
1125
1126 $self->validate;
1127
1128 See "validate" in Validation::Class::Prototype for full documentation.
1129
1130 =proxy_method validate_document
1131
1132 $self->validate_document;
1133
1134 See "validate_document" in Validation::Class::Prototype for full
1135 documentation.
1136
1137 =proxy_method validate_method
1138
1139 $self->validate_method;
1140
1141 See "validate_method" in Validation::Class::Prototype for full
1142 documentation.
1143
1144 =proxy_method validate_profile
1145
1146 $self->validate_profile;
1147
1148 See "validate_profile" in Validation::Class::Prototype for full
1149 documentation.
1150
1151EXTENSIBILITY
1152
1153 Validation::Class does NOT provide method modifiers but can be easily
1154 extended with Class::Method::Modifiers.
1155
1156 before
1157
1158 before foo => sub { ... };
1159
1160 See "before method(s) => sub { ... }" in Class::Method::Modifiers for
1161 full documentation.
1162
1163 around
1164
1165 around foo => sub { ... };
1166
1167 See "around method(s) => sub { ... }" in Class::Method::Modifiers for
1168 full documentation.
1169
1170 after
1171
1172 after foo => sub { ... };
1173
1174 See "after method(s) => sub { ... }" in Class::Method::Modifiers for
1175 full documentation.
1176
1177SEE ALSO
1178
1179 Validation::Class does not validate blessed objects. If you need a
1180 means for validating object types you should use a modern object system
1181 like Moo, Mouse, or Moose. Alternatively, you could use decoupled
1182 object validators like Type::Tiny, Params::Validate or Specio.
1183
1184POD ERRORS
1185
1186 Hey! The above document had some coding errors, which are explained
1187 below:
1188
1189 Around line 96:
1190
1191 Unknown directive: =keyword
1192
1193 Around line 120:
1194
1195 Unknown directive: =keyword
1196
1197 Around line 142:
1198
1199 Unknown directive: =keyword
1200
1201 Around line 164:
1202
1203 Unknown directive: =keyword
1204
1205 Around line 210:
1206
1207 Unknown directive: =keyword
1208
1209 Around line 428:
1210
1211 Unknown directive: =keyword
1212
1213 Around line 473:
1214
1215 Unknown directive: =keyword
1216
1217 Around line 528:
1218
1219 Unknown directive: =keyword
1220
1221 Around line 555:
1222
1223 Unknown directive: =keyword
1224
1225 Around line 564:
1226
1227 Unknown directive: =keyword
1228
1229 Around line 585:
1230
1231 Unknown directive: =keyword
1232
1233 Around line 615:
1234
1235 Unknown directive: =keyword
1236
1237 Around line 638:
1238
1239 Unknown directive: =keyword
1240
1241 Around line 669:
1242
1243 Unknown directive: =keyword
1244
1245 Around line 764:
1246
1247 Unknown directive: =keyword
1248
1249 Around line 837:
1250
1251 Unknown directive: =method
1252
1253 Around line 871:
1254
1255 Unknown directive: =keyword
1256
1257 Around line 908:
1258
1259 Unknown directive: =method
1260
1261 Around line 1182:
1262
1263 =back without =over
1264
1265
README.mkdn
1# NAME
2
3Validation::Class - Powerful Data Validation Framework
4
5# VERSION
6
7version 7.900057
8
9# SYNOPSIS
10
11 use Validation::Class::Simple::Streamer;
12
13 my $params = {username => 'admin', password => 's3cret'};
14 my $input = Validation::Class::Simple::Streamer->new(params => $params);
15
16 # check username parameter
17 $input->check('username')->required->between('5-255');
18 $input->filters([qw/trim strip/]);
19
20 # check password parameter
21 $input->check('password')->required->between('5-255')->min_symbols(1);
22 $input->filters([qw/trim strip/]);
23
24 # run validate
25 $input->validate or die $input->errors_to_string;
26
27# DESCRIPTION
28
29Validation::Class is a scalable data validation library with interfaces for
30applications of all sizes. The most common usage of Validation::Class is to
31transform class namespaces into data validation domains where consistency and
32reuse are primary concerns. Validation::Class provides an extensible framework
33for defining reusable data validation rules. It ships with a complete set of
34pre-defined validations and filters referred to as
35["directives"](https://metacpan.org/pod/Validation::Class::Directives#DIRECTIVES).
36
37The core feature-set consist of self-validating methods, validation profiles,
38reusable validation rules and templates, pre and post input filtering, class
39inheritance, automatic array handling, and extensibility (e.g. overriding
40default error messages, creating custom validators, creating custom input
41filters and much more). Validation::Class promotes DRY (don't repeat yourself)
42code. The main benefit in using Validation::Class is that the architecture is
43designed to increase the consistency of data input handling. The following is
44a more traditional usage of Validation::Class, using the DSL to construct a
45validator class:
46
47 package MyApp::Person;
48
49 use Validation::Class;
50
51 # data validation template
52 mixin basic => {
53 required => 1,
54 max_length => 255,
55 filters => [qw/trim strip/]
56 };
57
58 # data validation rules for the username parameter
59 field username => {
60 mixin => 'basic',
61 min_length => 5
62 };
63
64 # data validation rules for the password parameter
65 field password => {
66 mixin => 'basic',
67 min_length => 5,
68 min_symbols => 1
69 };
70
71 package main;
72
73 my $person = MyApp::Person->new(username => 'admin', password => 'secr3t');
74
75 # validate rules on the person object
76 unless ($person->validates) {
77 # handle the failures
78 warn $person->errors_to_string;
79 }
80
81 1;
82
83# QUICKSTART
84
85If you are looking for a simple in-line data validation module built
86using the same tenets and principles as Validation::Class, please review
87[Validation::Class::Simple](https://metacpan.org/pod/Validation::Class::Simple) or [Validation::Class::Simple::Streamer](https://metacpan.org/pod/Validation::Class::Simple::Streamer). If you
88are new to Validation::Class, or would like more information on the
89underpinnings of this library and how it views and approaches data validation,
90please review [Validation::Class::Whitepaper](https://metacpan.org/pod/Validation::Class::Whitepaper). Please review the
91["GUIDED-TOUR" in Validation::Class::Cookbook](https://metacpan.org/pod/Validation::Class::Cookbook#GUIDED-TOUR) for a detailed step-by-step look into
92how Validation::Class works.
93
94# KEYWORDS
95
96## adopt
97
98The adopt keyword (or adt) copies configuration and functionality from
99other Validation::Class classes. The adopt keyword takes three arguments, the
100name of the class to be introspected, and the configuration type and name to be
101recreated. Basically, anything you can configure using a Validation::Class
102keyword can be adopted into other classes using this keyword with the exception
103of coderefs registered using the build keyword. Please note! If you are adopting
104a field declaration which has an associated mixin directive defined on the
105target class, you must adopt the mixin explicitly if you wish it's values to be
106interpolated.
107
108 package MyApp::Exployee;
109
110 use Validate::Class;
111 use MyApp::Person;
112
113 adopt MyApp::Person, mixin => 'basic';
114 adopt MyApp::Person, field => 'first_name';
115 adopt MyApp::Person, field => 'last_name';
116 adopt MyApp::Person, profile => 'has_fullname';
117
118 1;
119
120## attribute
121
122The attribute keyword (or has) registers a class attribute, i.e. it creates an
123accessor (getter and setter) on the class. Attribute declaration is flexible and
124only requires an attribute name to be configured. Additionally, the attribute
125keyword can takes two arguments, the attribute's name and a scalar or coderef to
126be used as it's default value.
127
128 package MyApp::Person;
129
130 use Validate::Class;
131
132 attribute 'first_name' => 'Peter';
133 attribute 'last_name' => 'Venkman';
134 attribute 'full_name' => sub {
135 join ', ', $_[0]->last_name, $_[0]->first_name
136 };
137
138 attribute 'email_address';
139
140 1;
141
142## build
143
144The build keyword (or bld) registers a coderef to be run at instantiation much
145in the same way the common BUILD routine is used in modern OO frameworks.
146
147 package MyApp::Person;
148
149 use Validation::Class;
150
151 build sub {
152
153 my ($self, $args) = @_;
154
155 # run after instantiation in the order defined
156
157 };
158
159 1;
160
161The build keyword takes one argument, a coderef which is passed the instantiated
162class object.
163
164## directive
165
166The directive keyword (or dir) registers custom validator directives to be used
167in your field definitions. Please note that custom directives can only be used
168with field definitions. This is a means of extending the list of directives per
169instance. See the list of core directives, [Validation::Class::Directives](https://metacpan.org/pod/Validation::Class::Directives),
170or review [Validation::Class::Directive](https://metacpan.org/pod/Validation::Class::Directive) for insight into creating your own
171CPAN installable directives.
172
173 package MyApp::Person;
174
175 use Validate::Class;
176
177 # define a custom class-level directive
178 directive 'blacklisted' => sub {
179
180 my ($self, $field, $param) = @_;
181
182 if (defined $field->{blacklisted} && defined $param) {
183 if ($field->{required} || $param) {
184 if (exists_in_blacklist($field->{blacklisted}, $param)) {
185 my $handle = $field->label || $field->name;
186 $field->errors->add("$handle has been blacklisted");
187 return 0;
188 }
189 }
190 }
191
192 return 1;
193
194 };
195
196 field 'email_address' => {
197 blacklisted => '/path/to/blacklist'
198 email => 1,
199 };
200
201 1;
202
203The directive keyword takes two arguments, the name of the directive and a
204coderef which will be used to validate the associated field. The coderef is
205passed four ordered parameters; a directive object, the class prototype object,
206the current field object, and the matching parameter's value. The validator
207(coderef) is evaluated by its return value as well as whether it altered any
208error containers.
209
210## document
211
212The document keyword (or doc) registers a data matching profile which can be
213used to validate heiarchal data. It will store a hashref with pre-define path
214matching rules for the data structures you wish to validate. The "path matching
215rules", which use a specialized object notation, referred to as the document
216notation, can be thought of as a kind-of simplified regular expression which is
217executed against the flattened data structure. The following are a few general
218use-cases:
219
220 package MyApp::Person;
221
222 use Validation::Class;
223
224 field 'string' => {
225 mixin => [':str']
226 };
227
228 # given this JSON data structure
229 {
230 "id": "1234-A",
231 "name": {
232 "first_name" : "Bob",
233 "last_name" : "Smith",
234 },
235 "title": "CIO",
236 "friends" : [],
237 }
238
239 # select id to validate against the string rule
240 document 'foobar' =>
241 { 'id' => 'string' };
242
243 # select name -> first_name/last_name to validate against the string rule
244 document 'foobar' =>
245 {'name.first_name' => 'string', 'name.last_name' => 'string'};
246
247 # or
248 document 'foobar' =>
249 {'name.*_name' => 'string'};
250
251 # select each element in friends to validate against the string rule
252 document 'foobar' =>
253 { 'friends.@' => 'string' };
254
255 # or select an element of a hashref in each element in friends to validate
256 # against the string rule
257 document 'foobar' =>
258 { 'friends.@.name' => 'string' };
259
260The document declaration's keys should follow the aforementioned document
261notation schema and it's values should be strings which correspond to the names
262of fields (or other document declarations) that will be used to preform the
263data validation. It is possible to combine document declarations to validate
264hierarchical data that contains data structures matching one or more document
265patterns. The following is an example of what that might look like.
266
267 package MyApp::Person;
268
269 use Validation::Class;
270
271 # data validation rule
272 field 'name' => {
273 mixin => [':str'],
274 pattern => qr/^[A-Za-z ]+$/,
275 max_length => 20,
276 };
277
278 # data validation map / document notation schema
279 document 'friend' => {
280 'name' => 'name'
281 };
282
283 # data validation map / document notation schema
284 document 'person' => {
285 'name' => 'name',
286 'friends.@' => 'friend'
287 };
288
289 package main;
290
291 my $data = {
292 "name" => "Anita Campbell-Green",
293 "friends" => [
294 { "name" => "Horace" },
295 { "name" => "Skinner" },
296 { "name" => "Alonzo" },
297 { "name" => "Frederick" },
298 ],
299 };
300
301 my $person = MyApp::Person->new;
302
303 unless ($person->validate_document(person => $data)) {
304 warn $person->errors_to_string if $person->error_count;
305 }
306
307 1;
308
309Alternatively, the following is a more verbose data validation class using
310traditional styling and configuration.
311
312 package MyApp::Person;
313
314 use Validation::Class;
315
316 field 'id' => {
317 mixin => [':str'],
318 filters => ['numeric'],
319 max_length => 2,
320 };
321
322 field 'name' => {
323 mixin => [':str'],
324 pattern => qr/^[A-Za-z ]+$/,
325 max_length => 20,
326 };
327
328 field 'rating' => {
329 mixin => [':str'],
330 pattern => qr/^\-?\d+$/,
331 };
332
333 field 'tag' => {
334 mixin => [':str'],
335 pattern => qr/^(?!evil)\w+/,
336 max_length => 20,
337 };
338
339 document 'person' => {
340 'id' => 'id',
341 'name' => 'name',
342 'company.name' => 'name',
343 'company.supervisor.name' => 'name',
344 'company.supervisor.rating.@.*' => 'rating',
345 'company.tags.@' => 'name'
346 };
347
348 package main;
349
350 my $data = {
351 "id" => "1234-ABC",
352 "name" => "Anita Campbell-Green",
353 "title" => "Designer",
354 "company" => {
355 "name" => "House of de Vil",
356 "supervisor" => {
357 "name" => "Cruella de Vil",
358 "rating" => [
359 { "support" => -9,
360 "guidance" => -9
361 }
362 ]
363 },
364 "tags" => [
365 "evil",
366 "cruelty",
367 "dogs"
368 ]
369 },
370 };
371
372 my $person = MyApp::Person->new;
373
374 unless ($person->validate_document(person => $data)) {
375 warn $person->errors_to_string if $person->error_count;
376 }
377
378 1;
379
380Additionally, the following is yet another way to validate a document by
381passing the document specification directly instead of by name.
382
383 package MyApp::Person;
384
385 use Validation::Class;
386
387 package main;
388
389 my $data = {
390 "id" => "1234-ABC",
391 "name" => "Anita Campbell-Green",
392 "title" => "Designer",
393 "company" => {
394 "name" => "House of de Vil",
395 "supervisor" => {
396 "name" => "Cruella de Vil",
397 "rating" => [
398 { "support" => -9,
399 "guidance" => -9
400 }
401 ]
402 },
403 "tags" => [
404 "evil",
405 "cruelty",
406 "dogs"
407 ]
408 },
409 };
410
411 my $spec = {
412 'id' => { max_length => 2 },
413 'name' => { mixin => ':str' },
414 'company.name' => { mixin => ':str' },
415 'company.supervisor.name' => { mixin => ':str' },
416 'company.supervisor.rating.@.*' => { pattern => qr/^(?!evil)\w+/ },
417 'company.tags.@' => { max_length => 20 },
418 };
419
420 my $person = MyApp::Person->new;
421
422 unless ($person->validate_document($spec => $data)) {
423 warn $person->errors_to_string if $person->error_count;
424 }
425
426 1;
427
428## ensure
429
430The ensure keyword (or ens) is used to convert a pre-existing method
431into an auto-validating method. The auto-validating method will be
432registered and function as if it was created using the method keyword.
433The original pre-existing method will be overridden with a modifed version
434which performs the pre and/or post validation routines.
435
436 package MyApp::Person;
437
438 use Validation::Class;
439
440 sub register {
441 ...
442 }
443
444 ensure register => {
445 input => ['name', '+email', 'username', '+password', '+password2'],
446 output => ['+id'], # optional output validation, dies on failure
447 };
448
449 package main;
450
451 my $person = MyApp::Person->new(params => $params);
452
453 if ($person->register) {
454 # handle the successful registration
455 }
456
457 1;
458
459The ensure keyword takes two arguments, the name of the method to be
460overridden and a hashref of required key/value pairs. The hashref may
461have an input key (e.g. input, input\_document, input\_profile, or input\_method).
462The \`input\` key (specifically) must have a value which must be either an
463arrayref of fields to be validated, or a scalar value which matches (a
464validation profile or auto-validating method name). The hashref may also have
465an output key (e.g. output, output\_document, output\_profile, or output\_method).
466The \`output\` key (specifically) must have a value which must be either an
467arrayref of fields to be validated, or a scalar value which matches (a
468validation profile or auto-validating method name). Whether and what the
469method returns is yours to decide. The method will return undefined if
470validation fails. The ensure keyword wraps and functions much in the same way
471as the method keyword.
472
473## field
474
475The field keyword (or fld) registers a data validation rule for reuse and
476validation in code. The field name should correspond with the parameter name
477expected to be passed to your validation class or validated against.
478
479 package MyApp::Person;
480
481 use Validation::Class;
482
483 field 'username' => {
484 required => 1,
485 min_length => 1,
486 max_length => 255
487 };
488
489The field keyword takes two arguments, the field name and a hashref of key/values
490pairs known as directives. For more information on pre-defined directives, please
491review the ["list of core directives"](https://metacpan.org/pod/Validation::Class::Directives#DIRECTIVES).
492
493The field keyword also creates accessors which provide easy access to the
494field's corresponding parameter value(s). Accessors will be created using the
495field's name as a label having any special characters replaced with an
496underscore.
497
498 # accessor will be created as send_reminders
499 field 'send-reminders' => {
500 length => 1
501 };
502
503Please note that prefixing field names with a double plus-symbol instructs the
504register to merge your declaration with any pre-existing declarations within the
505same scope (e.g. fields imported via loading roles), whereas prefixing field
506names with a single plus-symbol instructs the register to overwrite any
507pre-existing declarations.
508
509 package MyApp::Person;
510
511 use Validation::Class;
512
513 set role => 'MyApp::User';
514
515 # append existing field and overwrite directives
516 field '++email_address' => {
517 required => 1
518 };
519
520 # redefine existing field
521 field '+login' => {
522 required => 1
523 };
524
525 1;
526
527## filter
528
529The filter keyword (or flt) registers custom filters to be used in your field
530definitions. It is a means of extending the pre-existing filters declared by
531the ["filters directive"](https://metacpan.org/pod/Validation::Class::Directive::Filters) before
532instantiation.
533
534 package MyApp::Person;
535
536 use Validate::Class;
537
538 filter 'flatten' => sub {
539 $_[0] =~ s/[\t\r\n]+/ /g;
540 return $_[0];
541 };
542
543 field 'biography' => {
544 filters => ['trim', 'strip', 'flatten']
545 };
546
547 1;
548
549The filter keyword takes two arguments, the name of the filter and a
550coderef which will be used to filter the value the associated field. The coderef
551is passed the value of the field and that value MUST be operated on directly.
552The coderef should also return the transformed value.
553
554## load
555
556The load keyword (or set), which can also be used as a class method, provides
557options for extending the current class by declaring roles, requirements, etc.
558
559The process of applying roles, requirement, and other settings to the current
560class mainly involves introspecting the namespace's methods and merging relevant
561parts of the prototype configuration.
562
563## load-classes
564
565The \`classes\` (or class) option uses [Module::Find](https://metacpan.org/pod/Module::Find) to load all child classes
566(in-all-subdirectories) for convenient access through the
567["class" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#class) method, and when introspecting a larger
568application. This option accepts an arrayref or single argument.
569
570 package MyApp;
571
572 use Validation::Class;
573
574 load classes => ['MyApp::Domain1', 'MyApp::Domain2'];
575
576 package main;
577
578 my $app = MyApp->new;
579
580 my $person = $app->class('person'); # return a new MyApp::Person object
581
582 1;
583
584## load-requirements
585
586 package MyApp::User;
587
588 use Validate::Class;
589
590 load requirements => 'activate';
591
592 package MyApp::Person;
593
594 use Validation::Class;
595
596 load role => 'MyApp::User';
597
598 sub activate {}
599
600 1;
601
602The \`requirements\` (or required) option is used to ensure that if/when the class
603is used as a role the calling class has specific pre-existing methods. This
604option accepts an arrayref or single argument.
605
606 package MyApp::User;
607
608 use Validate::Class;
609
610 load requirements => ['activate', 'deactivate'];
611
612 1;
613
614## load-roles
615
616 package MyApp::Person;
617
618 use Validation::Class;
619
620 load role => 'MyApp::User';
621
622 1;
623
624The \`roles\` (or role) option is used to load and inherit functionality from
625other validation classes. These classes should be used and thought-of as roles
626although they can also be fully-functioning validation classes. This option
627accepts an arrayref or single argument.
628
629 package MyApp::Person;
630
631 use Validation::Class;
632
633 load roles => ['MyApp::User', 'MyApp::Visitor'];
634
635 1;
636
637## message
638
639The message keyword (or msg) registers a class-level error message template that
640will be used in place of the error message defined in the corresponding directive
641class if defined. Error messages can also be overridden at the individual
642field-level as well. See the [Validation::Class::Directive::Messages](https://metacpan.org/pod/Validation::Class::Directive::Messages) for
643instructions on how to override error messages at the field-level.
644
645 package MyApp::Person;
646
647 use Validation::Class;
648
649 field email_address => {
650 required => 1,
651 min_length => 3,
652 messages => {
653 # field-level error message override
654 min_length => '%s is not even close to being a valid email address'
655 }
656 };
657
658 # class-level error message overrides
659 message required => '%s is needed to proceed';
660 message min_length => '%s needs more characters';
661
662 1;
663
664The message keyword takes two arguments, the name of the directive whose error
665message you wish to override and a string which will be used to as a template
666which is feed to sprintf to format the message.
667
668## method
669
670The method keyword (or mth) is used to register an auto-validating method.
671Similar to method signatures, an auto-validating method can leverage
672pre-existing validation rules and profiles to ensure a method has the
673required pre/post-conditions and data necessary for execution.
674
675 package MyApp::Person;
676
677 use Validation::Class;
678
679 method 'register' => {
680
681 input => ['name', '+email', 'username', '+password', '+password2'],
682 output => ['+id'], # optional output validation, dies on failure
683 using => sub {
684
685 my ($self, @args) = @_;
686
687 # do something registrationy
688 $self->id(...); # set the ID field for output validation
689
690 return $self;
691
692 }
693
694 };
695
696 package main;
697
698 my $person = MyApp::Person->new(params => $params);
699
700 if ($person->register) {
701
702 # handle the successful registration
703
704 }
705
706 1;
707
708The method keyword takes two arguments, the name of the method to be created
709and a hashref of required key/value pairs. The hashref may have a \`using\` key
710whose value is the coderef to be executed upon successful validation. The
711\`using\` key is only optional when a pre-existing subroutine has the same name
712or the method being declared prefixed with a dash or dash-process-dash. The
713following are valid subroutine names to be called by the method declaration in
714absence of a \`using\` key. Please note, unlike the ensure keyword, any
715pre-existing subroutines will not be wrapped-and-replaced and can be executed
716without validation if called directly.
717
718 sub _name {
719 ...
720 }
721
722 sub _process_name {
723 ...
724 }
725
726The hashref may have an input key
727(e.g. input, input\_document, input\_profile, or input\_method). The \`input\` key
728(specifically) must have a value which must be either an arrayref of fields to
729be validated, or a scalar value which matches (a validation profile or
730auto-validating method name), which will be used to perform data validation
731**before** the aforementioned coderef has been executed. Whether and what the
732method returns is yours to decide. The method will return undefined if
733validation fails.
734
735 # alternate usage
736
737 method 'registration' => {
738 input => ['name', '+email', 'username', '+password', '+password2'],
739 output => ['+id'], # optional output validation, dies on failure
740 };
741
742 sub _process_registration {
743 my ($self, @args) = @_;
744 $self->id(...); # set the ID field for output validation
745 return $self;
746 }
747
748Optionally the hashref may also have an output key (e.g. output,
749output\_document, output\_profile, or output\_method). The \`output\` key
750(specifically) must have a value which must be either an arrayref of
751fields to be validated, or a scalar value which matches (a validation profile
752or auto-validating method name), which will be used to perform data validation
753**after** the aforementioned coderef has been executed.
754
755Please note that output validation failure will cause the program to die,
756the premise behind this decision is based on the assumption that given
757successfully validated input a routine's output should be predictable and
758if an error occurs it is most-likely a program error as opposed to a user error.
759
760See the ignore\_failure and report\_failure attributes on the prototype to
761control how method validation failures are handled.
762
763## mixin
764
765The mixin keyword (or mxn) registers a validation rule template that can be
766applied (or "mixed-in") to any field by specifying the mixin directive. Mixin
767directives are processed first so existing field directives will override any
768directives created by the mixin directive.
769
770 package MyApp::Person;
771
772 use Validation::Class;
773
774 mixin 'boilerplate' => {
775 required => 1,
776 min_length => 1,
777 max_length => 255
778 };
779
780 field 'username' => {
781 # min_length, max_length, .. required will be overridden
782 mixin => 'boilerplate',
783 required => 0
784 };
785
786Since version 7.900015, all classes are automatically configured with the
787following default mixins for the sake of convenience:
788
789 mixin ':flg' => {
790 required => 1,
791 min_length => 1,
792 filters => [qw/trim strip numeric/],
793 between => [0, 1]
794 };
795
796 mixin ':num' => {
797 required => 1,
798 min_length => 1,
799 filters => [qw/trim strip numeric/]
800 };
801
802 mixin ':str' => {
803 required => 1,
804 min_length => 1,
805 filters => [qw/trim strip/]
806 };
807
808Please note that the aforementioned mixin names are prefixed with a semi-colon but
809are treated as an exception to the rule. Prefixing mixin names with a double
810plus-symbol instructs the register to merge your declaration with any pre-existing
811declarations within the same scope (e.g. mixins imported via loading roles),
812whereas prefixing mixin names with a single plus-symbol instructs the register
813to overwrite any pre-existing declarations.
814
815 package MyApp::Moderator;
816
817 use Validation::Class;
818
819 set role => 'MyApp::Person';
820
821 # overwrite and append existing mixin
822 mixin '++boilerplate' => {
823 min_symbols => 1
824 };
825
826 # redefine existing mixin
827 mixin '+username' => {
828 required => 1
829 };
830
831 1;
832
833The mixin keyword takes two arguments, the mixin name and a hashref of key/values
834pairs known as directives.
835
836## profile
837
838The profile keyword (or pro) registers a validation profile (coderef) which as
839in the traditional use of the term is a sequence of validation routines that
840validates data relevant to a specific action.
841
842 package MyApp::Person;
843
844 use Validation::Class;
845
846 profile 'check_email' => sub {
847
848 my ($self, @args) = @_;
849
850 if ($self->email_exists) {
851 my $email = $self->fields->get('email');
852 $email->errors->add('Email already exists');
853 return 0;
854 }
855
856 return 1;
857
858 };
859
860 package main;
861
862 my $user = MyApp::Person->new(params => $params);
863
864 unless ($user->validate_profile('check_email')) {
865 # handle failures
866 }
867
868 1;
869
870The profile keyword takes two arguments, a profile name and coderef which will
871be used to execute a sequence of actions for validation purposes.
872
873# METHODS
874
875## new
876
877The new method instantiates a new class object, it performs a series of actions
878(magic) required for the class to function properly, and for that reason, this
879method should never be overridden. Use the build keyword for hooking into the
880instantiation process.
881
882In the event a foreign (pre-existing) \`new\` method is detected, an
883\`initialize\_validator\` method will be injected into the class containing the
884code (magic) necessary to normalize your environment.
885
886 package MyApp::Person;
887
888 use Validation::Class;
889
890 # hook
891 build sub {
892
893 my ($self, @args) = @_; # on instantiation
894
895 };
896
897 sub new {
898
899 # rolled my own
900 my $self = bless {}, shift;
901
902 # execute magic
903 $self->initialize_validator;
904
905 }
906
907 1;
908
909## prototype
910
911The prototype method (or proto) returns an instance of the associated class
912prototype. The class prototype is responsible for manipulating and validating
913the data model (the class). It is not likely that you'll need to access
914this method directly, see [Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype).
915
916 package MyApp::Person;
917
918 use Validation::Class;
919
920 package main;
921
922 my $person = MyApp::Person->new;
923
924 my $prototype = $person->prototype;
925
926 1;
927
928# PROXY METHODS
929
930Validation::Class mostly provides sugar functions for modeling your data
931validation requirements. Each class you create is associated with a prototype
932class which provides the data validation engine and keeps your class namespace
933free from pollution, please see [Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype) for more
934information on specific methods and attributes. Validation::Class injects a few
935proxy methods into your class which are basically aliases to the corresponding
936prototype class methods, however it is possible to access the prototype directly
937using the proto/prototype methods.
938
939## class
940
941 $self->class;
942
943See ["class" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#class) for full documentation.
944
945## clear\_queue
946
947 $self->clear_queue;
948
949See ["clear\_queue" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#clear_queue) for full documentation.
950
951## error\_count
952
953 $self->error_count;
954
955See ["error\_count" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#error_count) for full documentation.
956
957## error\_fields
958
959 $self->error_fields;
960
961See ["error\_fields" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#error_fields) for full documentation.
962
963## errors
964
965 $self->errors;
966
967See ["errors" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#errors) for full documentation.
968
969## errors\_to\_string
970
971 $self->errors_to_string;
972
973See ["errors\_to\_string" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#errors_to_string) for full documentation.
974
975## get\_errors
976
977 $self->get_errors;
978
979See ["get\_errors" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#get_errors) for full documentation.
980
981## get\_fields
982
983 $self->get_fields;
984
985See ["get\_fields" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#get_fields) for full documentation.
986
987## get\_hash
988
989 $self->get_hash;
990
991See ["get\_hash" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#get_hash) for full documentation.
992
993## get\_params
994
995 $self->get_params;
996
997See ["get\_params" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#get_params) for full documentation.
998
999## get\_values
1000
1001 $self->get_values;
1002
1003See ["get\_values" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#get_values) for full documentation.
1004
1005## fields
1006
1007 $self->fields;
1008
1009See ["fields" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#fields) for full documentation.
1010
1011## filtering
1012
1013 $self->filtering;
1014
1015See ["filtering" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#filtering) for full documentation.
1016
1017## ignore\_failure
1018
1019 $self->ignore_failure;
1020
1021See ["ignore\_failure" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#ignore_failure) for full documentation.
1022
1023## ignore\_intervention
1024
1025 $self->ignore_intervention;
1026
1027See ["ignore\_intervention" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#ignore_intervention) for full documentation.
1028
1029## ignore\_unknown
1030
1031 $self->ignore_unknown;
1032
1033See ["ignore\_unknown" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#ignore_unknown) for full documentation.
1034
1035## is\_valid
1036
1037 $self->is_valid;
1038
1039See ["is\_valid" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#is_valid) for full documentation.
1040
1041## param
1042
1043 $self->param;
1044
1045See ["param" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#param) for full documentation.
1046
1047## params
1048
1049 $self->params;
1050
1051See ["params" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#params) for full documentation.
1052
1053## plugin
1054
1055 $self->plugin;
1056
1057See ["plugin" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#plugin) for full documentation.
1058
1059## queue
1060
1061 $self->queue;
1062
1063See ["queue" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#queue) for full documentation.
1064
1065## report\_failure
1066
1067 $self->report_failure;
1068
1069See ["report\_failure" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#report_failure) for full
1070documentation.
1071
1072## report\_unknown
1073
1074 $self->report_unknown;
1075
1076See ["report\_unknown" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#report_unknown) for full documentation.
1077
1078## reset\_errors
1079
1080 $self->reset_errors;
1081
1082See ["reset\_errors" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#reset_errors) for full documentation.
1083
1084## reset\_fields
1085
1086 $self->reset_fields;
1087
1088See ["reset\_fields" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#reset_fields) for full documentation.
1089
1090## reset\_params
1091
1092 $self->reset_params;
1093
1094See ["reset\_params" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#reset_params) for full documentation.
1095
1096## set\_errors
1097
1098 $self->set_errors;
1099
1100See ["set\_errors" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#set_errors) for full documentation.
1101
1102## set\_fields
1103
1104 $self->set_fields;
1105
1106See ["set\_fields" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#set_fields) for full documentation.
1107
1108## set\_params
1109
1110 $self->set_params;
1111
1112See ["set\_params" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#set_params) for full documentation.
1113
1114## set\_method
1115
1116 $self->set_method;
1117
1118See ["set\_method" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#set_method) for full documentation.
1119
1120## stash
1121
1122 $self->stash;
1123
1124See ["stash" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#stash) for full documentation.
1125
1126## validate
1127
1128 $self->validate;
1129
1130See ["validate" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#validate) for full documentation.
1131
1132## validate\_document
1133
1134 $self->validate_document;
1135
1136See ["validate\_document" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#validate_document) for full documentation.
1137
1138## validate\_method
1139
1140 $self->validate_method;
1141
1142See ["validate\_method" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#validate_method) for full documentation.
1143
1144## validate\_profile
1145
1146 $self->validate_profile;
1147
1148See ["validate\_profile" in Validation::Class::Prototype](https://metacpan.org/pod/Validation::Class::Prototype#validate_profile) for full documentation.
1149
1150# UPGRADE
1151
1152Validation::Class is stable, its feature-set is complete, and is currently in
1153maintenance-only mode, i.e. Validation::Class will only be updated with minor
1154enhancements and bug fixes. However, the lessons learned will be incorporated
1155into a compelete rewrite uploaded under the namespace [Validation::Interface](https://metacpan.org/pod/Validation::Interface).
1156The Validation::Interface fork is designed to have a much simpler API with less
1157options and better execution, focused on validating hierarchical data as its
1158primarily objective.
1159
1160# EXTENSIBILITY
1161
1162Validation::Class does NOT provide method modifiers but can be easily extended
1163with [Class::Method::Modifiers](https://metacpan.org/pod/Class::Method::Modifiers).
1164
1165## before
1166
1167 before foo => sub { ... };
1168
1169See ["before method(s) => sub { ... }" in Class::Method::Modifiers](https://metacpan.org/pod/Class::Method::Modifiers#before-method-s-sub) for full
1170documentation.
1171
1172## around
1173
1174 around foo => sub { ... };
1175
1176See ["around method(s) => sub { ... }" in Class::Method::Modifiers](https://metacpan.org/pod/Class::Method::Modifiers#around-method-s-sub) for full
1177documentation.
1178
1179## after
1180
1181 after foo => sub { ... };
1182
1183See ["after method(s) => sub { ... }" in Class::Method::Modifiers](https://metacpan.org/pod/Class::Method::Modifiers#after-method-s-sub) for full
1184documentation.
1185
1186# SEE ALSO
1187
1188Validation::Class does not validate blessed objects. If you need a means for
1189validating object types you should use a modern object system like [Moo](https://metacpan.org/pod/Moo),
1190[Mouse](https://metacpan.org/pod/Mouse), or [Moose](https://metacpan.org/pod/Moose). Alternatively, you could use decoupled object
1191validators like [Type::Tiny](https://metacpan.org/pod/Type::Tiny), [Params::Validate](https://metacpan.org/pod/Params::Validate) or [Specio](https://metacpan.org/pod/Specio).
1192
1193# AUTHOR
1194
1195Al Newkirk <anewkirk@ana.io>
1196
1197# COPYRIGHT AND LICENSE
1198
1199This software is copyright (c) 2011 by Al Newkirk.
1200
1201This is free software; you can redistribute it and/or modify it under
1202the same terms as the Perl 5 programming language system itself.
1203
1204# POD ERRORS
1205
1206Hey! **The above document had some coding errors, which are explained below:**
1207
1208- Around line 1195:
1209
1210 =back without =over
1211