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