Valiant.pm untested

filter: Statementstmt 0.0% 0 / 2 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 0.0% 0 / 2 SCAR -
1 package Valiant;
2  
3 our $VERSION = '0.001019';
4 $VERSION = eval $VERSION;
5  
6 1;
7  
8 =head1 NAME
9  
10 Valiant - Object validation inspired by Ruby on Rails and more.
11  
12 =begin html
13  
14 <a href="https://github.com/jjn1056/valiant/actions"><img src="https://github.com/jjn1056/valiant/actions/workflows/linux.yml/badge.svg"></a>
15 <a href="https://github.com/jjn1056/valiant/actions"><img src="https://github.com/jjn1056/valiant/actions/workflows/macos.yml/badge.svg"></a>
16 <a href="https://github.com/jjn1056/valiant/actions"><img src="https://github.com/jjn1056/valiant/actions/workflows/windows.yml/badge.svg"></a>
17 <a href="https://metacpan.org/pod/Valiant"><img src="https://badge.fury.io/pl/Valiant.svg"></a>
18 <a href="https://codecov.io/github/jjn1056/Valiant/?branch=main"><img alt="Coverage" src="https://codecov.io/github/jjn1056/Valiant/coverage.svg?branch=main"></a>
19  
20 =end html
21  
22 =head1 SYNOPSIS
23  
24 package Local::Person;
25  
26 use Moo;
27 use Valiant::Validations;
28 use Valiant::Filters;
29  
30 has name => (is=>'ro');
31 has age => (is=>'ro');
32  
33 filters_with => 'Trim';
34  
35 validates name => (
36 length => {
37 maximum => 10,
38 minimum => 3,
39 }
40 );
41  
42 validates age => (
43 numericality => {
44 is_integer => 1,
45 less_than => 200,
46 },
47 );
48  
49 validates_with 'MySpecialValidator' => (arg1=>'foo', arg2=>'bar');
50  
51 my $person = Local::Person->new(
52 name => 'Ja',
53 age => 300,
54 );
55  
56 $person->validate;
57 $person->valid; # FALSE
58 $person->invalid; # TRUE
59  
60 my %errors = $person->errors->to_hash(full_messages=>1);
61  
62 # \%errors = +{
63 # age => [
64 # "Age must be less than 200",
65 # ],
66 # name => [
67 # "Name is too short (minimum is 3 characters)',
68 # ],
69 # };
70  
71 =head1 DESCRIPTION
72  
73 Domain level validations for L<Moo> or L<Moose> classes and related capabilities such as attribute
74 filtering and internationalization. Provides a domain specific language
75 which allows you to defined for a given class what a valid state for an instance of that
76 class would be and to gather reportable error messages. Used to defined constraints
77 related to business logic or for validating user input (for example via CGI forms).
78  
79 When we say domain level or business logic validation, what we mean is that
80 invalid data is a possible and expected state that needs to be evaluated and reported to
81 the end user for correction. For example when writing a web application you might have
82 a form that requests user profile information (such as name, DOB, address, etc). Its an
83 expected condition that the user might submit form data that is invalid in some way (such
84 as a DOB that is in the future) but is still 'well formed' and is able to be processed.
85 In these cases your business logic would be to inform the user of the incorrect data and
86 request fixes (rather than simply throw a 500 server error and giving up).
87  
88 This differs from type constraints (such as L<Type::Tiny>) that you might put on your
89 L<Moo> attributes which are used to express when attributes have values that are
90 so unacceptable that no further work can be done and an exception must be thrown.
91  
92 In fact you will note that when using validations that you generally won't add type constraints
93 on your L<Moo> attributes. That's because type constraints are applied when the
94 object is instantiated and throw an exception when they fail. Validations on the other
95 hand permit you to create the object and collect all the validation failure conditions.
96 Also since you have a created object you can do more complex validations (such as those
97 that involve the state of more than one attribute). You would only use attribute type
98 constraints when the created object would be in such an invalid state that one could
99 not correctly validate it anyway. An example of this might be when an attribute is assigned
100 an array value when a scalar is expected.
101  
102 L<Valiant> fits into a similar category as L<HTML::Formhander> and L<FormFu> although
103 its not HTML form specific. Prior art for this would be the validations system for ActiveRecords
104 in Ruby on Rails and the Javascript library class-validator.js, both of which the author reviewed
105 extensively when writing this code:
106  
107 L<https://rubyonrails.org>, L<https://github.com/typestack/class-validator>
108  
109 Documentation here details using L<Valiant> with L<Moo> or L<Moose> based classes.
110 If you want to use L<Valiant> with L<DBIx::Class> you will also wish to review
111 L<DBIx::Class::Valiant> which details how L<Valiant> glues into L<DBIx::Class>.
112  
113 This document reviews all the bits of the L<Valiant> system as a whole (validations, filters,
114 internationalization, errores etc). You might also like to review API details from the following
115 files:
116  
117 L<Valiant::Validates>, a L<Moo::Role> which adds a validation API to your class, or L<Valiant::Validations>
118 which wraps L<Valiant::Validates> in an easy to use DSL (domain specific language).
119  
120 L<Valiant::Filterable>, a L<Moo::Role> which adds API to apply filtering to incoming attributes at
121 object creation time, or L<Valiant::Filters>, which wraps this in an easy to use DSL.
122  
123 L<Valiant::I18N>, API information on how we provide internationalized error messages for your
124 validations.
125  
126 L<Valiant::Validator> and L<Valiant::Filter> which provides details about validations and filters that
127 are packaged with L<Valiant>.
128  
129 =head1 WHY OBJECT VALIDATION AS CLASS DATA?
130  
131 Validating the state of things is one of the most common tasks we perform. For example
132 a user might wish to change their profile information and you need to make sure that
133 the new settings conform to acceptable limits (such as the user first and last name
134 fits into the database and have acceptable characters, that a password is complex enough
135 and that an address is complete, etc). This logic can get tricky over time as a system grows in
136 complexity and edge cases need to be accounted for (for example for business reasons you might
137 wish to allow pre-existing users to conform to different password complexity constraints or
138 require newer users to supply more profile details).
139  
140 One approach to this is to build a specific validation object that receives and processes
141 data input. If the incoming data passes, you can proceed to send the data to your
142 storage object (such as L<DBIx::Class>) If it fails you then proceed to message the user the
143 failure conditions. For example this is the approach taken by L<HTML::Formhandler>.
144  
145 The approach has much to merit because it clearly separates your validation logic from
146 your storage logic. However when there is a big affinity between the two (such as when
147 all your HTML forms are very similar to your database tables) this can lead to a lot of
148 redundant code (such as defining the same field names in more than one class) which leads
149 to a maintainance and understanding burden. Also it can be hard to do proper validation
150 without access to a data object since often you will have validation logic that is dependent
151 on the current state of your data. For example you might require that a new password not
152 be one of the last three used; in this case you need access to the storage layer anyway.
153  
154 L<Valiant> offers a DSL (domain specific language) for adding validation meta data as
155 class data to your business objects. This allows you to maintain separation of
156 concerns between the job of validation and the rest of your business logic but also keeps
157 the validation work close to the object that actually needs it, preventing action at a
158 distance confusion. The actual validation code can be neatly encapsulated into standalone
159 validator classes (subclasses based on L<Valiant::Validator> or L<Valiant::Validator::Each>)
160 so they can be reused across more than one business object. To bootstrap your validation work,
161 L<Valiant> comes with a good number of validators which cover many common cases, such as validating
162 string lengths and formats, date-time validation and numeric validations. Lastly, the validation meta data
163 which is added via the DSL can aggregate across consumed roles and inherited classes. So you can
164 create shared roles and base classes which defined validations that are used in many places.
165  
166 Once you have decorated your business logic classes with L<Valiant> validations, you can
167 run those validations on blessed instances of those classes and inspect errors. There is
168 also some introspection capability making it possible to do things like generate display UI
169 from your errors.
170  
171 =head1 EXAMPLES
172  
173 The following are some example cases of how one can use L<Valiant> to perform object validation
174  
175 =head2 The simplest possible case
176  
177 At its most simple, a validation can be just a reference to a subroutine which adds validation
178 error messages based on conditions you code:
179  
180 package Local::Simple
181  
182 use Valiant::Validations;
183 use Moo;
184  
185 has name => (is => 'ro');
186 has age => (is => 'ro');
187  
188 validates_with sub {
189 my ($self, $opts) = @_;
190 $self->errors->add(name => "Name is too long") if length($self->name) > 20;
191 $self->errors->add(age => "Age can't be negative") if $self->age < 1;
192 };
193  
194 my $simple = Local::Simple->new(
195 name => 'A waaay too loooong name', # more than 20 characters
196 age => -10, # less than 1
197 );
198  
199 $simple->validate;
200 $simple->valid; # FALSE
201 $simple->invalid; # TRUE
202  
203 my %errors = $simple->errors->to_hash(full_messages=>1);
204  
205 #\%errors = {
206 # age => [
207 # "Age can't be negative",
208 # ],
209 # name => [
210 # "Name is too long",
211 # ],
212 #}
213  
214 The subroutine reference that the C<validates_with> keyword accepts will receive the blessed
215 instance as the first argument and a hash of options as the second. Options are added as
216 additional arguments after the subroutine reference. This makes it easier to create parameterized
217 validation methods:
218  
219 package Local::Simple2;
220  
221 use Valiant::Validations;
222 use Moo;
223  
224 has name => (is => 'ro');
225 has age => (is => 'ro');
226  
227 validates_with \&check_length, length_max => 20;
228 validates_with \&check_age_lower_limit, min => 5;
229  
230 sub check_length {
231 my ($self, $opts) = @_;
232 $self->errors->add(name => "is too long") if length($self->name) > $opts->{length_max};
233 }
234  
235 sub check_age_lower_limit {
236 my ($self, $opts) = @_;
237 $self->errors->add(age => "can't be lower than $opts->{min}") if $self->age < $opts->{min};
238 }
239  
240 my $simple2 = Local::Simple2->new(
241 name => 'A waaay too loooong name',
242 age => -10,
243 );
244  
245 $simple2->validate;
246 $simple2->valid; # FALSE
247 $simple2->invalid; # TRUE
248  
249 my %errors = $simple2->errors->to_hash(full_messages=>1);
250  
251 #\%errors = {
252 # age => [
253 # "Age can't be lower than 5",
254 # ],
255 # name => [
256 # "Name is too long",
257 # ],
258 #}
259  
260 The validation methods have access to the fully blessed instance so you can create complex
261 validation rules based on your business requirements, including retrieving information from
262 shared storage classes.
263  
264 Since many of your validations will be directly on attributes of your object, you can use the
265 C<validates> keyword which offers some shortcuts and better code reusability for attributes.
266 We can rewrite the last class as follows:
267  
268 package Local::Simple3;
269  
270 use Valiant::Validations;
271 use Moo;
272  
273 has name => (is => 'ro');
274 has age => (is => 'ro');
275  
276 validates name => ( \&check_length => { length_max => 20 } );
277 validates age => ( \&check_age_lower_limit => { min => 5 } );
278  
279 sub check_length {
280 my ($self, $attribute, $value, $opts) = @_;
281 $self->errors->add($attribute => "is too long", $opts) if length($value) > $opts->{length_max};
282 }
283  
284 sub check_age_lower_limit {
285 my ($self, $attribute, $value, $opts) = @_;
286 $self->errors->add($attribute => "can't be lower than $opts->{min}", $opts) if $value < $opts->{min};
287 }
288  
289 my $simple3 = Local::Simple2->new(
290 name => 'A waaay too loooong name',
291 age => -10,
292 );
293  
294 $simple3->validate;
295  
296 my %errors = $simple3->errors->to_hash(full_messages=>1);
297  
298 #\%errors = {
299 # age => [
300 # "Age can't be lower than 5",
301 # ],
302 # name => [
303 # "Name is too long",
304 # ],
305 #}
306  
307 Using the C<validates> keyword allows you to name the attribute for which the validations are intended.
308 When you do this the signature of the arguments for the subroutine reference changes to included both
309 the attribute name (as a string) and the current attribute value. This is useful since you can now
310 use the validation method across different attributes, avoiding hardcoding its name into your validation rule.
311 One difference from C<validates_with> you will note is that if you want to pass arguments as parameter options
312 you need to use a hashref and not a hash. This is due to the fact that C<validates> can take a list of
313 validators, each with its own arguments. For example you could have the following:
314  
315 validates name => (
316 \&check_length => { length_max => 20 },
317 \&looks_like_a_name,
318 \&is_unique_name_in_database,
319 );
320  
321 Also, similiar to the C<has> keyword that L<Moo> imports, you can use an arrayref of attribute name for grouping
322 those with the same validation rules:
323  
324 validates ['first_name', 'last_name'] => ( \&check_length => { length_max => 20 } );
325  
326 At this point you can see how to write fairly complex and parameterized validations on your attributes
327 directly or on the object as a whole (using C<validates> for attributes and C<validates_with> for validations
328 that are not directly tied to an attribute but instead validate the object as a whole). However it is
329 often ideal to isolate your validation logic into a stand alone class to promote code reuse as well as
330 better separate your valiation logic from your classes.
331  
332 =head2 Using a validator class
333  
334 Although you could use subroutine references for all your validation if you did so you'd likely end
335 up with a lot of repeated code across your classes. This is because a lot of validations are standard
336 (such as string length and allowed characters, numeric ranges and so on). As a result you will likely
337 build at least some custom validators and make use of the prepacked ones that ship with L<Valiant> (see L<Valiant::Validator>).
338 Lets return to one of the earlier examples that used C<valiates_with> but instead of using a subroutine
339 reference we will rewrite it as a custom validator:
340  
341 package Local::Person::Validator::Custom;
342  
343 use Moo;
344 with 'Valiant::Validator';
345  
346 has 'max_name_length' => (is=>'ro', required=>1);
347 has 'min_age' => (is=>'ro', required=>1);
348  
349 sub validate {
350 my ($self, $object, $opts) = @_;
351 $object->errors->add(name => "is too long", $opts) if length($object->name) > $self->max_name_length;
352 $object->errors->add(age => "can't be lower than @{[ $self->min_age ]}", $opts) if $object->age < $self->min_age;
353 }
354  
355 And use it in a class:
356  
357 package Local::Person;
358  
359 use Valiant::Validations;
360 use Moo;
361  
362 has name => (is => 'ro');
363 has age => (is => 'ro');
364  
365 validates_with Custom => (
366 max_name_length => 20,
367 min_age => 5,
368 );
369  
370 my $person = Local::Person->new(
371 name => 'A waaay too loooong name',
372 age => -10,
373 );
374  
375 $person->validate;
376 $person->invalid; # TRUE
377  
378 my %errors = $person->errors->to_hash(full_messages=>1) };
379  
380 #\%errors = +{
381 # age => [
382 # "Age can't be lower than 5",
383 # ],
384 # name => [
385 # "Name is too long",
386 # ],
387 #};
388  
389 A custom validator is just a class that does the C<validate> method (although I recommend that you
390 consume the L<Valiant::Validator> role as well; this might be required at some point). When this validator
391 is added to a class, it is instantiated once with any provided arguments (which are passed to C<new> as init_args).
392 Each time you call validate, it runs the C<validate> method with the following signature:
393  
394 sub validate {
395 my ($self, $object, $opts) = @_;
396 $object->errors->add(...) if ...
397 }
398  
399 Where C<$self> is the validator object, C<$object> is the current instance of the class you are
400 validating and C<$opts> is the options hashref.
401  
402 Within this method you can do any special or complex validation and add error messages to the C<$object>
403 based on its current state.
404  
405 =head2 Custom Validator Namespace Resolution
406  
407 When you use a custom validator class namepart (either via C<validates> or
408 C<validates_with>) we search thru a number of namespaces to find a match. This is done
409 to allow you to create increasingly custom valiators for your classes. Basically we start with the
410 package name of the class which is adding the validator, add "::Validator::${namepart}" and then look
411 down the namespace tree for a loadable file. If we don't find a match in your project package
412 namespace we then also look in the two globally shared namespaces C<Valiant::ValidatorX> and
413 C<Valiant::Validator>. If we still don't find a match we then throw an exception. For example
414 if your package is named C<Local::Person> as in the class above and you specify the C<Custom> validator
415 we will search for it in all the namespaces below, in order written:
416  
417 Local::Person::Validator::Custom
418 Local::Validator::Custom
419 Validator::Custom
420 Valiant::ValidatorX::Custom
421 Valiant::Validator::Custom
422  
423 This lookup only happens once when your classes are first loaded, so this will cause a a delay in startup
424 but not at runtime. However the delay probably makes L<Valiant> unsuitable for non persistant applications
425 such as CGI web applications or possibly scripts that run as part of a cron job.
426  
427 B<NOTE:> The namespace C<Valiant::Validator> is reserved for validators that ship with L<Valiant>. The
428 C<Valiant::ValidatorX> namespace is reserved for additional validators on CPAN that are packaged separately
429 from L<Valiant>. If you wish to share a custom validator that you wrote the proper namespace to use on
430 CPAN is C<Valiant::ValidatorX>.
431  
432 You can also prepend your validator name with '+' which will cause L<Valiant> to ignore the namespace
433 resolution and try to load the class directly. For example:
434  
435 validates_with '+App::MyValidator';
436  
437 Will try to load the class C<App::MyValidator> and use it as a validator directly (or throw an exception if
438 it fails to load).
439  
440 =head2 Validator classes and attributes
441  
442 Since many of your validations will be on your class's attributes, L<Valiant> makes it easy to use custom
443 and prepackaged validator classes directly on attributes. All validator classes which operate on attributes
444 must consume the role L<Valiant::Validator::Each>. Here's an example of a class which is using several of
445 the prepackaged attribute validator classes that comes with L<Valiant>.
446  
447 package Local::Task;
448  
449 use Valiant::Validations;
450 use Moo;
451  
452 has priority => (is => 'ro');
453 has description => (is => 'ro');
454 has due_date => (is => 'ro');
455  
456 validates priority => (
457 presence => 1,
458 numericality => { only_integer => 1, between => [1,10] },
459 );
460  
461 validates description => (
462 presence => 1,
463 length => [10,60],
464 );
465  
466 validates due_date => (
467 presence => 1,
468 date => 'is_future',
469 );
470  
471 In this case our class defines three attributes, 'priority' (which defined how important a task
472 is), 'description' (which is a human read description of the task that needs to happen) and
473 a 'due_date' (which is when the task should be completed). We then have validations which
474 place some constraints on the allowed values for these attributes. Our validations state that:
475  
476 'priority' must be defined, must be an integer and the number must be from 1 thru 10.
477 'description' must be defined and a string that is longer than 10 characters but less than 60.
478 'due_date' must be in a date format (YYYY-MM-DD or eg. '2000-01-01') and also must be a future date.
479  
480 This class uses the following validators: L<Valiant::Validator::Presence>, to verify that the attribute
481 has a meaningful defined value; L<Valiant::Validator::Numericality>, to verify the value is an integer and is
482 between 1 and 10; L<Valiant::Validator::Length>, to check the length of a string and
483 L<Valiant::Validator::Date> to verify that the value looks like a date and is a date in the future.
484  
485 Canonically a validator class accepts a hashref of options, but many of the packaged validators also
486 accept shortcut forms for the most common use cases. For example since its common to require a date be
487 sometime in the future you can write "date => 'is_future'". Documentation for these shortcut forms are detailed
488 in each validator class.
489  
490 =head2 Creating a custom attribute validator class
491  
492 Creating your own custom attribute validator classes is just as easy as it was for creating a general
493 validator class. You need to write a L<Moo> class that consumes the L<Valiant::Validator::Each> role
494 and provides a C<validates_each> method with the following signature:
495  
496 sub validates_each {
497 my ($self, $object, $attribute, $value, $opts) = @_;
498 }
499  
500 Where C<$self> is the validator class instance (this is created once when the validator is added to the class),
501 C<$object> is the instance of the class you are validating, C<$attribute> is the string name of the attribute
502 this validation is running on, C<$value> is the current attribute's value and C<$opts> is a hashref of options
503 passed to the class. For example, here is simple Boolean truth validator:
504  
505 package MyApp::Validator::True;
506  
507 use Moo;
508  
509 with 'Valiant::Validator::Each';
510  
511 sub validate_each {
512 my ($self, $object, $attribute, $value, $opts) = @_;
513 $object->errors->add($attribute, 'is not a true value', $opts) unless $value;
514 }
515  
516 And example of using it in a class:
517  
518 package MyApp::Foo;
519  
520 use Moo;
521 use Valiant::Validations;
522  
523 has 'bar' => ('ro'=>1);
524  
525 validates bar => (True => +{}); # No arguments passed to MyApp::Validator::True->new()
526  
527 Two things to note: There is no meaning assigned to the return value of C<validate_each> (or of C<validates>).
528 Also you should remember to pass C<$opts> as the third argument to the C<add> method. Even if you are not
529 using the options hashref in your custom validator, it might contain values that influence other aspects
530 of the framework, such as how the error message is formatted.
531  
532 When resolving an attribute validator namepart, the same rules described above for general validator classes apply.
533  
534 =head1 PREPACKAGED VALIDATOR CLASSES
535  
536 Please see L<Valiant::Validator> for a list of all the valiators that are shipped with
537 L<Valiant> and/or search CPAN for validators in the L<Valiant::ValidatorX> namespace.
538  
539 =head1 TYPE CONSTRAINT SUPPORT
540  
541 If you are comfortable using common type contraint libaries such as L<Type::Tiny> you can
542 use those directly as validation rules much in the same way you can use subroutine references.
543  
544 package Local::Test::Check;
545  
546 use Moo;
547 use Valiant::Validations;
548 use Types::Standard 'Int';
549  
550 has drinking_age => (is=>'ro');
551  
552 validates drinking_age => (
553 Int->where('$_ >= 21'), +{
554 message => 'is too young to drink!',
555 },
556 );
557  
558 When using this option you should use a library system such as L<Type::Tiny> that provides
559 an object with a C<check> method that returns a boolean indicating if the constraint was passed
560 or not. There are several such library systems on CPAN that you might find useful in helping
561 you to write validations.
562  
563 Please note this is just wrapping L<Valiant::Validator::Check> so if you need more control
564 you might prefer to use the validator class.
565  
566 =head1 INHERITANCE AND ROLES
567  
568 You can aggregate validation rules via inheritance and roles. This makes it so that if you
569 have a number of classes with similar validation rules you can avoid repeating yourself.
570 Example:
571  
572 package Person;
573  
574 use Moo;
575 use Valiant::Validations;
576  
577 has 'name' => (is=>'ro',);
578 has 'age' => (is=>'ro');
579  
580 validates name => (
581 presence => 1,
582 length => [3,20],
583 );
584  
585 validates age => (
586 numericality => {
587 only_integer => 1,
588 greater_than => 0,
589 less_than => 150,
590 },
591 );
592  
593 package IsRetirementAge;
594  
595 use Moo::Role;
596 use Valiant::Validations;
597  
598 requires 'age';
599  
600 validates age => (
601 numericality => {
602 greater_than => 64,
603 },
604 );
605  
606 package Retiree;
607  
608 use Moo;
609 use Valiant::Validations;
610  
611 extends 'Person';
612 with 'IsRetirementAge';
613  
614 1;
615  
616 my $retiree = Retiree->new(name=>'Molly Millions', age=>24);
617  
618 $retiree->invalid; # true
619  
620 my %errors = $object->errors->to_hash(full_messages=>1);
621 # \%errors = +{
622 # age => ["Age must be greater than 64" ]
623 # }
624  
625 =head1 GLOBAL ATTRIBUTE VALIDATOR OPTIONS
626  
627 All attribute validators can accept the following options. Options can be added to each
628 validator separately (if you have several) or can be added globally to the end
629 of the validator rules. Global rules run first, followed by those applied to
630 each validator.
631  
632 =head2 allow_undef
633  
634 If the attribute value is undef, skip validation and allow it.
635  
636 package Person;
637  
638 use Moo;
639 use Valiant::Validations;
640  
641 has 'name' => (is=>'ro',);
642 has 'age' => (is=>'ro');
643  
644 validates name => (
645 format => 'alphabetic',
646 length => [3,20],
647 allow_undef => 1, # Skip BOTH 'format' and 'length' validators if 'name' is undefined.
648 );
649  
650 validates age => (
651 numericality => {
652 only_integer => 1,
653 greater_than => 0,
654 less_than => 150,
655 allow_undef => 1, # Skip only the 'numericality' validator if 'age' is undefined
656 },
657 );
658
659 =head2 allow_blank
660  
661 If the attribute is blank (that is its one of undef, '', or a scalar composing only
662 whitespace) skip validation and allow it. This is similar to the C<allow_undef> option
663 except it allows a broader definition of 'blank'. Useful for form validations.
664  
665 =head2 if / unless
666  
667 Accepts a coderef or the name of a method which executes and is expected to
668 return true or false. If false we skip the validation (or true for C<unless>).
669 Recieves the object, the attribute name, value to be checked and the options hashref
670 as arguments.
671  
672 You can set more than one value to these with an arrayref:
673  
674 if => ['is_admin', sub { ... }, 'active_account'],
675  
676 Example:
677  
678 package Person;
679  
680 use Moo;
681 use Valiant::Validations;
682  
683 has 'name' => (is=>'ro',);
684 has 'password' => (is=>'ro');
685  
686 validates name => (
687 format => 'alphabetic',
688 length => [3,20],
689 );
690  
691 validates password => (
692 length => [12,32],
693 with => \&is_a_secure_looking_password,
694 unless => sub {
695 my ($self, $attr, $value, $opts) = @_;
696 $self->name eq 'John Napiorkowski'; # John can make an insecure password if he wants!
697 },
698 );
699  
700 =head2 message
701  
702 Provide a global error message override for the constraint. Message can be formated in the
703 same way as the second argument to 'errors->add' and will accept a string,
704 a translation tag, a reference to a string or a reference to a function. Using
705 this will override the custom error message provided by the validator.
706  
707 package Person;
708  
709 use Moo;
710 use Valiant::Validations;
711  
712 has 'name' => (is=>'ro',);
713 has 'age' => (is=>'ro');
714  
715 validates name => (
716 format => 'alphabetic',
717 length => [3,20],
718 message => 'Unacceptable Name', # Overrides both the 'format' and 'length' messages.
719 );
720  
721 validates age => (
722 presence => 1,
723 numericality => {
724 only_integer => 1,
725 greater_than => 0,
726 less_than => 150,
727 message => 'Age given is not valid', # overrides just the 'numericality' messages
728 # and not the 'presence' message.
729 },
730 );
731  
732 Please not that many validators also provide error type specific messages for custom
733 errors (as well as the ability to setup your own errors in a localization file.) Using
734 this attribute is the easiest but probably not always your best option.
735  
736 Messages can be:
737  
738 =over 4
739  
740 =item A string
741  
742 If a string this is the error message recorded.
743  
744 validates name => (
745 format => 'alphabetic',
746 length => [3,20],
747 message => 'Unacceptable Name',
748 );
749  
750 =item A translation tag
751  
752 use Valiant::I18N;
753  
754 validates name => (
755 format => 'alphabetic',
756 length => [3,20],
757 message => _t('bad_name'),
758 );
759  
760 This will look up a translated version of the tag. See L<Valiant::I18N> for more details.
761  
762 =item A scalar reference
763  
764 validates name => (
765 format => 'alphabetic',
766 length => [3,20],
767 message => \'Unacceptable {{attribute}}',
768 );
769  
770 Similar to string but we will expand any placeholder variables which are indicated by the
771 '{{' and '}}' tokens (which are removed from the final string). You can use any placeholder
772 that is a key in the options hash (and you can pass additional values when you add an error).
773 By default the following placeholder expansions are available attribute (the attribute name),
774 value (the current attribute value), model (the human name of the model containing the
775 attribute and object (the actual object instance that has the error).
776  
777 =item A subroutine reference
778  
779 validates name => (
780 format => 'alphabetic',
781 length => [3,20],
782 message => sub {
783 my ($self, $attr, $value, $opts) = @_;
784 return "Unacceptable $attr!";
785 }
786 );
787  
788 Similar to the scalar reference option just more flexible since you can write custom code
789 to build the error message. For example you could return different error messages based on
790 the identity of a person. Also if you return a translation tag instead of a simple string
791 we will attempt to resolve it to a translated string (see L<Valiant::I18N>).
792  
793 =back
794  
795 =head2 strict
796  
797 When true instead of adding a message to the errors list, will throw exception with the
798 error instead. If the true value is a string (basically anything other than a 1) we use the
799 string given as the message. If the true value is the name of a class that provides a C<throw>
800 message, will use that instead. Lastly if the value is a coderef we call that.
801  
802 =head2 on
803  
804 A scalar or array reference of contexts that can be used to control the situation ('context')
805 under which the validation is executed. If you specify an C<on> context that
806 validation will only run if you pass that context via C<validate>. However if you
807 don't set a context for the validate (in other words you don't set an C<on> value)
808 then that validation ALWAYS runs (whether or not you set a context via C<validate>.
809 Basically not setting a context means validation runs in all contexts and none.
810 Examples:
811  
812 package Local::Test::Person;
813  
814 use Moo;
815 use Valiant::Validations;
816 use Valiant::I18N;
817  
818 has age => (is=>'ro');
819  
820 validates age => (
821 numericality => {
822 is_integer => 1,
823 less_than => 200,
824 },
825 numericality => {
826 greater_than_or_equal_to => 18,
827 on => 'voter',
828 },
829 numericality => {
830 greater_than_or_equal_to => 65,
831 on => 'retiree',
832 },
833 numericality => {
834 greater_than_or_equal_to => 100,
835 on => 'centarion',
836 },
837 );
838  
839 my $person = Local::Test::Person->new(age=>50);
840  
841 $person->validate();
842 $person->valid; # True.
843  
844 $person->validate(context=>'retiree');
845 $person->valid; # False; "Age must be greater than or equal to 65"
846  
847 $person->validate(context=>'voter');
848 $person->valid; # True.
849  
850 $person->validate(context=>'centarion');
851 $person->valid; # False; "Age must be greater than or equal to 100"
852  
853 my $another_person = Local::Test::Person->new(age=>"not a number");
854  
855 $another_person->validate();
856 $another_person->valid; # False "Age does not look like an integer"
857  
858 In this example you can see that since the first validation does not set an C<on> context
859 it always runs no matter what context you set via C<validate> (even when you don't set one).
860 So we always check that the value is an integer.
861  
862 Basically the rule to remember is validations with no C<on> option will run no matter the context
863 is set via validation options (or set automatically).
864 Validations with some C<on> option will only run in the specified context.
865  
866 So if your validation requests one or more contexts via C<on> they only run when at least one
867 of the passed contexts is matching. If your validation does not request a context via C<on>
868 then they match ANY or NONE contexts!
869  
870 =head1 GLOBAL MODEL VALIDATOR OPTIONS
871  
872 Model validators (added via C<validates_with>) support a subset of the the same options
873 as L</"GLOBAL ATTRIBUTE VALIDATOR OPTIONS">. These options work identically as described
874 in that section:
875  
876 if/unless
877 on
878 message
879 strict
880  
881 =head1 ERROR MESSAGES
882  
883 When you create an instance of a class that consumes the L<Valiant::Validates> role (typically
884 by using L<Valiant::Validations> to import the standard methods into the class) that role will
885 add an attribute called C<errors> to your class. This attribute will contain an instance of
886 L<Valiant::Errors>, which is a collection class that contains a list of errors (instances of
887 L<Valiant::Error>) along with methods to add, retrieve and introspect errors. You should
888 review L<Valiant::Errors> for the full class API since we will only coverage the most commonly
889 used methods in our example.
890  
891 The most common use cases you will have is adding errors and checking for and recovering error
892 messages.
893  
894 =head2 Adding an error message.
895  
896 You can add an error message anywhere in your code, although most commonly you will do so in you
897 validation methods or validation callbacks. In all cases the method signature is the same:
898  
899 $object->errors->add($attribute_name, $error_message, \%opts);
900  
901 Where C<$attribute_name> is the string name of the attribute for which a validation error is being
902 recorded, C<$error_message> is one of the allowed error message types (see below for details) and
903 \%opts is a hashref of options and/or error message template variable expansions which is used to
904 influence how the error is processed.
905  
906 When the error is scoped to the C<$object> and not a particular attribute you can just use C<undef>
907 instead of an attribute name. This will record the error as a model error:
908  
909 $object->errors->add(undef, $error_message, \%opts);
910  
911 Lastly the C<%opts> hashref can be left off the method call if you don't have it. Generally its
912 passed as the last argument to C<validate> or any validation subroutine references
913 but if you are adding an error outside those methods you won't have it. For example you might wrap a
914 database call insidean eval and wish to add a model error if there's an exception.
915  
916 =head2 Error message types.
917  
918 When adding an error there's four options for what the value of <$error_message> can be and are described
919 above L</'GLOBAL ATTRIBUTE VALIDATOR OPTIONS'>
920  
921 =head2 Message priority
922  
923 L<Valiant> allows you to set messages at various points to give you a lot of flexibility in
924 customizing your response. You can add errors messages at the point you add it to the errors
925 collection, in the options for the validator and globally for all validators in a chain. For
926 example:
927  
928 package MyApp::Errors;
929  
930 use Moo;
931 use Valiant::Validations;
932  
933 has name => (is=>'ro');
934  
935 validates name => (
936 with => {
937 cb => sub {
938 my ($self, $attr, $value, $opts) = @_;
939 $self->errors->add($attr, 'is always in error!', $opts); #LAST
940 },
941 message => 'has wrong value', #FIRST
942 },
943 message => 'has some sort of error', #SECOND
944 );
945  
946 Here you can see error messages at three levels. Here's the resolution order:
947  
948 Messages added to the errors collection via ->add are last
949 Messages added globally to a validation clause are second
950 Messages added via the 'message' option for a validator is first
951  
952 In this case the error would be "Name has wrong value".
953  
954 B<Note> for the outermost global message, please keep in mind that it will override all the error
955 messages of any of the validators in the clause.
956  
957 =head2 Accessing and displaying error messages
958  
959 Once you have validated your object (via the ->validate method) you can check for for validate
960 state and review or display any errors.
961  
962 =head3 Checking for errors on a validated object
963  
964 You can use the C<valid> or C<invalid> methods on your object to check for its validation state.
965 These methods won't run validations, unless they have not yet been run, so you can call them as
966 often as you want without incurring a runtime performance penalty.
967  
968 B<NOTE> However if you pass arguments such as C<context> then any existing validations are cleared
969 and validations are re run.
970  
971 $object->validate;
972 $object->valid; # TRUE if there are no errors, FALSE otherwise
973 $object->invalid # Opposite of 'valid'
974  
975 You can also just check the size of the errors collection (size of 0 means no errors):
976  
977 $object->validate;
978 $object->errors->size;
979  
980 To make this a bit easier the C<validate> method returns its calling object so you can chain methods:
981  
982 $object->validate->valid;
983  
984 =head3 Retrieving error messages
985  
986 The L<Valiant::Errors> collection object gives you a few ways to retrieve error messages. Assuming
987 there is a model with errors like the following for these examples and discussion:
988  
989 $model->errors->add(undef, "Your Form is invalid");
990 $model->errors->add(name => "is too short");
991 $model->errors->add(name => "has disallowed characters");
992 $model->errors->add(age => "must be above 5");
993 $model->errors->add(email => "does not look like an email address");
994 $model->errors->add(password => "is too short");
995 $model->errors->add(password => "can't look like your name");
996 $model->errors->add(password => "needs to contain both numbers and letters");
997  
998 =over 4
999  
1000 =item Getting all the errors at once, or groups of errors
1001  
1002 You can get all the error messages in a simple array with either the C<messages> or
1003 C<full_messages> method on the errors collection:
1004  
1005 For C<messages>:
1006  
1007 is_deeply [$model->errors->messages], [
1008 "Your Form is invalid",
1009 "is too short",
1010 "has disallowed characters",
1011 "must be above 5",
1012 "does not look like an email address",
1013 "is too short",
1014 "can't look like your name",
1015 "needs to contain both numbers and letters",
1016 ];
1017  
1018 For C<full_messages>:
1019  
1020 is_deeply [$model->errors->full_messages], [
1021 "Your Form is invalid",
1022 "Name is too short",
1023 "Name has disallowed characters",
1024 "Age must be above 5",
1025 "Email does not look like an email address",
1026 "Password is too short",
1027 "Password can't look like your name",
1028 "Password needs to contain both numbers and letters",
1029 ];
1030  
1031 This combines all the attribute and model message into a flat list. Please not that
1032 the current order is the order in which messages are added as errors to the errors
1033 collection.
1034  
1035 The only difference between C<messages> and C<full_messages> is that the latter will
1036 combine your error message with a human readable version of your attribute name. By
1037 default this is just a title cased version of the attribute name but you can customize
1038 this via setting a translation (see L</INTERNATONALIZATION>). C<full_messages> by
1039 default uses the following expansion template: "{{attribute}} {{message}}" however you can
1040 customize this by setting the C<format> key in your translation file (again see L</INTERNATONALIZATION>).
1041  
1042 If you just want the model level errors you can use C<model_messages>:
1043  
1044 is_deeply [$model->errors->model_messages], [
1045 "Your Form is invalid",
1046 ];
1047  
1048 There is a similar pair of methods for just getting messages associated with attributes:
1049 C<attribute_messages> and C<full_attribute_messages>:
1050  
1051 is_deeply [$model->errors->attribute_messages], [
1052 "is too short",
1053 "has disallowed characters",
1054 "must be above 5",
1055 "does not look like an email address",
1056 "is too short",
1057 "can't look like your name",
1058 "needs to contain both numbers and letters",
1059 ];
1060  
1061 is_deeply [$model->errors->full_attribute_messages], [
1062 "Name is too short",
1063 "Name has disallowed characters",
1064 "Age must be above 5",
1065 "Email does not look like an email address",
1066 "Password is too short",
1067 "Password can't look like your name",
1068 "Password needs to contain both numbers and letters",
1069 ];
1070  
1071 Lastly you can retrieve all the error messages as a hash using the C<to_hash> method. This
1072 return a hash where the hash keys refer to attributes with errors (or in the case of model
1073 errors the key is '*') and the value is an arrayref of the error(s) associated with that key.
1074 The C<to_hash> method accepts an argument to control if the error messages return using
1075 the C<full_messages> value or the C<messages> value:
1076  
1077 is_deeply +{ $model->errors->to_hash }, {
1078 "*" => [
1079 "Your Form is invalid",
1080 ],
1081 age => [
1082 "must be above 5",
1083 ],
1084 email => [
1085 "does not look like an email address",
1086 ],
1087 name => [
1088 "is too short",
1089 "has disallowed characters",
1090 ],
1091 password => [
1092 "is too short",
1093 "can't look like your name",
1094 "needs to contain both numbers and letters",
1095 ],
1096 };
1097  
1098 is_deeply +{ $model->errors->to_hash(full_messages=>1) }, {
1099 "*" => [
1100 "Your Form is invalid",
1101 ],
1102 age => [
1103 "Age must be above 5",
1104 ],
1105 email => [
1106 "Email does not look like an email address",
1107 ],
1108 name => [
1109 "Name is too short",
1110 "Name has disallowed characters",
1111 ],
1112 password => [
1113 "Password is too short",
1114 "Password can't look like your name",
1115 "Password needs to contain both numbers and letters",
1116 ],
1117 };
1118  
1119 =item Getting errors for individual attributes
1120  
1121 Similar to the method that allows you to get the errors just for the model you
1122 can get errors for individual attibutes with the C<messages_for> and C<full_messages_for>
1123 methods:
1124  
1125 is_deeply [$model->errors->full_messages_for('password')], [
1126 "Password is too short",
1127 "Password can't look like your name",
1128 "Password needs to contain both numbers and letters",
1129 ];
1130  
1131 is_deeply [$model->errors->messages_for('password')], [
1132 "is too short",
1133 "can't look like your name",
1134 "needs to contain both numbers and letters",
1135 ];
1136  
1137 If you request errors for an attribute that has none you will get an empty array.
1138  
1139 Please note that these methods always return arrays even if the case where you have only
1140 a single error.
1141  
1142 =item Searching for errors, interating and introspection.
1143  
1144 L<Valiant::Errors> contains additional methods for iterating over error collections,
1145 searching for errors and introspecting errors. Please refer to that package for
1146 full documentation and examples.
1147  
1148 =back
1149  
1150 =head1 NESTED OBJECTS AND ARRAYS
1151  
1152 In some cases you may have complex, nested objects or objects that contain arrays of
1153 values which need validation. When an object is nested as a attribute under another
1154 object it may itself contain validations. For these more complex cases we provide
1155 two validator classes L<Valiant::Validator::Object> and L<Valiant::Validator::Array>.
1156 You should refer to documentation in each of those validators for API level overview and
1157 examples.
1158  
1159 =head1 INTERNATONALIZATION
1160  
1161 Internationalization for L<Valiant> will concern our ability to create tags that represent
1162 human readable strings for different languages. Generally we will create tags, which are
1163 abstract labels representing a message, and then map those lables to various human languages
1164 which we wish to support. In using L<Valiant::I18N> with L<Valiant> there are generally
1165 three things that we will internationalize:
1166  
1167 =over 4
1168  
1169 =item error messages
1170  
1171 =item attribute names
1172  
1173 =item model names
1174  
1175 =back
1176  
1177 L<Valiant> when looking up tags for translations will follow a precedence order which allows
1178 you to set base translations for your models, errors and attributes but then override them.
1179 For example lets say you have a class defined as so:
1180  
1181 package Retiree;
1182  
1183 use Moo;
1184 use Valiant::Validations;
1185 use Valiant::I18N;
1186  
1187 extends 'Person'
1188  
1189 has 'name' => (is=>'ro');
1190  
1191 validates 'name', sub {
1192 my ($self, $attribute, $value, $opts) = @_;
1193 $self->errors->add($attribute => _t('too_long'), +{%$opts, count=>36}) if length($value||'') > 36;
1194 };
1195  
1196 This defines a class with one attribute that has a single validation which makes sure the 'name'
1197 is less than 36 characters. Let's see how translations are resolved:
1198  
1199 my $p = Retiree->new(name=>'x'x100);
1200 $p->invalid;
1201  
1202 warn $p->model_name->human; # returns "Retiree"
1203  
1204 When resolving a translated version of the Model name we check the following tags:
1205  
1206 valiant.models.retiree
1207 valiant.models.person
1208  
1209 Basically we check each model in the @ISA list, which lets you create a base set of translations
1210 that you can override. If none of the tags are defined as translations then we just use the
1211 humanized version of the package name. We follow a similar process for translating attributes:
1212  
1213 warn $p->human_attribute_name('name'); " returns "Name"
1214  
1215 We check the following tags in order:
1216  
1217 valiant.attributes.retiree.name
1218 valiant.attributes.person.name
1219 attributes.name
1220  
1221 And again if we fail we just use the humanized version of the attribute name ("Name"). Errors
1222 are similar:
1223  
1224 warn $p->errors->messages_for('name'); "is too long (maximum is 36 characters)"
1225  
1226 We follow these tags:
1227  
1228 valiant.errors.models.retiree.attributes.name.too_long
1229 valiant.errors.models.retiree.too_long
1230 valiant.errors.models.person.attributes.name.too_long
1231 valiant.errors.models.person.too_long
1232 valiant.errors.messages.too_long
1233 errors.attributes.name.too_long
1234 errors.messages.too_long
1235  
1236 In this case there is no default so if the tag isn't found we just generate an error.
1237  
1238 =head2 Substitution Parameters and Pluralization
1239  
1240 In the case of error messages there is an additional complication in that often we need to
1241 customize the message base on the value of the attributes. For example when the attribute
1242 represents a number of items often the message for zero items will be different than for
1243 many (think "You have 3 items in you bag, the minimum is 5" versus "You have no items in
1244 your bag, the minimum is 5"). The rules for this can be complex depending on the language.
1245 Therefore in the case of error messages you will need the ability to return a different
1246 string for those cases. We can see this example in the last error message example above
1247 which specified a maximum of 36 characters. The way this works with errors is that when
1248 adding a error message the final argument hashref is passed to the translator:
1249  
1250 $self->errors->add($attribute => _t('too_long'), +{%$opts, count=>36}) if length($value||'') > 36;
1251  
1252 And the translation tag for this looks like:
1253  
1254 {
1255 en => {
1256 errors => {
1257 messages => {
1258 too_long => {
1259 one => 'is too long (maximum is 1 character)',
1260 other => 'is too long (maximum is {{count}} characters)',
1261 },
1262 }
1263 }
1264 }
1265 }
1266  
1267 Here you can see that when 'count' is 1 we use one translation but when its more than one we
1268 have a slightly different tag. Any keys passed to $opts can be used as a subsitution parameter
1269 but the 'count' parameter is special since its also used for pluralization. In the case when
1270 'count' is 0, 1 or more than one we match subkeys as in the example give (when count is 0 we match
1271 'zero'; when its 1 we match 'one' and if something else we match 'other'.
1272  
1273 Please be careful what you pass as options to substitution placeholders since you can open up
1274 injection style attackes on your code.
1275  
1276 =head2 How roles impact translation tag lookups
1277  
1278 Since we can't count on role application order we don't by default use roles as translation
1279 tag namespace lookups in the same way as inherited classes. However since it can be useful
1280 to set translation tags at the role level we allow you to indicate that a role should be used
1281 in the lookup. Roles so added will be checked after an base classes. You mark a role for
1282 lookup via the 'push_to_i18n_lookup' keyword:
1283  
1284 package TestRole;
1285  
1286 use Moo::Role;
1287 use Valiant::Validations;
1288 use Valiant::I18N;
1289  
1290 validates_with sub {
1291 my ($self) = @_;
1292 $self->errors->add(undef, 'Failed TestRole');
1293 $self->errors->add('name');
1294 $self->errors->add(name => _t 'bad', +{ all=>1 } );
1295 };
1296  
1297 push_to_i18n_lookup;
1298  
1299 Then we'd use 'test_role' as an extra lookup key. For example if we composed "TestRole" into
1300 the 'Retiree" class above and then checked the model name we'd use this lookup:
1301  
1302 valiant.models.retiree
1303 valiant.models.person
1304 valiant.models.role_name
1305  
1306 for the 'name' attribute:
1307  
1308 We check the following tags in order:
1309  
1310 valiant.attributes.retiree.name
1311 valiant.attributes.person.name
1312 valiant.attributes.role_name.name
1313 attributes.name
1314  
1315 And finally for the 'too_long' error tag:
1316  
1317 valiant.errors.models.retiree.attributes.name.too_long
1318 valiant.errors.models.retiree.too_long
1319 valiant.errors.models.person.attributes.name.too_long
1320 valiant.errors.models.person.too_long
1321 valiant.errors.models.role_name.attributes.name.too_long
1322 valiant.errors.models.role_name.too_long
1323 valiant.errors.messages.too_long
1324 errors.attributes.name.too_long
1325 errors.messages.too_long
1326  
1327 =head2 full_messages* version messages*
1328  
1329 When getting the text of error messages you can use either the 'full_messages*' or 'messages'
1330 methods (see L<Valiant::Errors>, L<Valiant::Error>). The only difference between the 'full' and
1331 non full messages is that the 'full' versions combine the attribute name with the translated text
1332 of the error. The default pattern for this is: "{{attribute}} {{message}}" but you can override
1333 this as usual following a pattern similar to error lookups.
1334  
1335 valiant.errors.models.person.attributes.name.format
1336 valiant.errors.models.person.format
1337 errors.format.attributes.name
1338 errors.format
1339
1340 As before we'd also check base classes and roles as indicated.
1341  
1342 =head1 FILTERING
1343  
1344 Quite often you will wish to allow your users a bit of leeway when providing information.
1345 For example you might want incoming data for a field to be in all capitals, and to be free from
1346 any extra post or trailing whitespace. You could test for these in a validation and return
1347 error conditions when they are present. However that is not always the best user experience. In
1348 cases where you are willing to accept such input from users but you want to 'clean up' the data
1349 before trying to validate it you can use filters.
1350  
1351 For now please see L<Valiant::Filters> and L<Valiant::Filters> for API level documentations on
1352 filters as well as some examples. Also see L<Valiant::Filter> for a list of the prepackaged filter
1353 that ship with L<Valiant>
1354  
1355 =head1 HTML FORM GENERATION
1356  
1357 HTML Form generation is not specifically added to the L<Valiant> validation code, but there is
1358 a set of packages designed to work with L<Valiant> as well as L<DBIx::Class::Valiant> ORM integration:
1359 L<Valiant::HTML::FormBuilder>, L<Valiant::HTML::Form> and L<Valiant::HTML::FormTags>. This code
1360 is currently under active development although I expect that the publically documented API
1361 is very likely to remain stable. Here's a simple example of what this form integration looks like;
1362 for now you'll need to refer to the API docs and the example application for more on how to use
1363 this.
1364  
1365 Given a model like:
1366  
1367 package Local::Person;
1368  
1369 use Moo;
1370 use Valiant::Validations;
1371  
1372 has first_name => (is=>'ro');
1373 has last_name => (is=>'ro');
1374  
1375 validates ['first_name', 'last_name'] => (
1376 length => {
1377 maximum => 20,
1378 minimum => 3,
1379 }
1380 );
1381  
1382 Wrap a formbuilder object around it and generate HTML form field controls:
1383  
1384 use Valiant::HTML::Form 'form_for';
1385  
1386 my $person = Local::Person->new(first_name=>'J', last_name=>'Napiorkowski');
1387 $person->validate;
1388  
1389 print form_for($person, sub {
1390 my $fb = shift;
1391 return $fb->label('first_name'),
1392 $fb->input('first_name'),
1393 $fb->errors_for('first_name', +{ class=>'invalid-feedback' }),
1394 $fb->label('last_name'),
1395 $fb->input('last_name'),
1396 $fb->errors_for('last_name'+{ class=>'invalid-feedback' });
1397 });
1398  
1399 Generates something like:
1400  
1401 <form accept-charset="UTF-8" id="new_person" method="post">
1402 <label for="person_first_name">First Name</label>
1403 <input id="person_first_name" name="person.first_name" type="text" value="John"/>
1404 <div class='invalid-feedback'>First Name is too short (minimum is 3 characters).</div>
1405 <label for="person_last_name">Last Name</label>
1406 <input id="person_last_name" name="person.last_name" type="text" value="Napiorkowski"/>
1407 </form>
1408  
1409 =head1 DEBUGGING
1410  
1411 You can set the %ENV variable C<VALIANT_DEBUG> to a number ranging 1 to 3 which will give
1412 increasing more detailed debugging output that should assist you if things are not working
1413 as expected. Debug level 1 only returns messages during the startup / compile stage so its
1414 reasonable safe to run even in a production environment since it should not impact run time
1415 performance.
1416  
1417 =head1 SEE ALSO
1418  
1419 There's no lack of validation systems on CPAN. I've used (and contributed) to
1420 L<HTML::FormHandler> and L<Data::MuForm>. I've also used L<HTML::FormFu>. Recently I
1421 spotted L<Form::Tiny> which is a similar DSL style system as L<Valiant> but with a smaller
1422 footprint and sane looking code. This list is not exhaustive, just stuff I've either used or
1423 reviewed.
1424  
1425 L<Valiant>, L<Valiant::Validations>, L<Valiant::Validates>, L<Valiant::Filters>,
1426 L<Valiant::Filterable>
1427  
1428 =head1 DEDICATIONS
1429  
1430 This module is eternally dedicated to the memory of my beloved animal companions; our Bernese
1431 Mountain Dog 'Tornado' who we lost to cancer in 16 August 2020; our Akita 'Sunshine' who passed
1432 from complications due to age on July 14th, 2021 and their pup 'Squeaker' also lost to cancer on
1433 December 18th, 2021.
1434  
1435 The distribution as a whole is dedicated in their memory, but specifically the core L<Valiant>
1436 code is dedicated to Tornado, the DBIC integration work to Sunshine and the HTML form generation
1437 and templating code to Squeaker.
1438  
1439 If you find this code useful, if it helps your company or makes you money please consider a donation
1440 to help other owners of these dog breeds or aid in the quest to end dog cancer:
1441  
1442 L<http://www.berner.org/pages/charities.php>, L<https://akitarescue.rescuegroups.org/info/donate>,
1443 L<https://wearethecure.org/donations/>.
1444  
1445 Or to any dog charity that fits best with your personal beliefs and economic means.
1446  
1447 =head1 COPYRIGHT & LICENSE
1448
1449 Copyright 2022, John Napiorkowski L<email:jjnapiork@cpan.org>
1450
1451 This library is free software; you can redistribute it and/or modify it under
1452 the same terms as Perl itself.
1453  
1454 =cut
1455