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