Valida...totype(3pm)
β¨ Validation::Class::Prototype(3pm) β¨ β User Contributed Perl Documentation, bestie. No cap.
π NAME π
Validation::Class::Prototype β Data Validation Engine for Validation::Class Classes.
πΈ VERSION πΈ
version 7.900059
π¦ DESCRIPTION π¦
Validation::Class::Prototype is the validation engine used by proxy via Validation::Class whose methods are aliases to the methods defined here. Please see Validation::Class::Simple for a quick introduction on how to get started.
π ATTRIBUTES π
π attributes π
The attributes attribute provides access to simple attributes registered on the the calling class. This attribute is a Validation::Class::Mapping object containing hashref objects and CANNOT be overridden.
π builders π
The builders attribute provides access to coderefs registered to hook into the instantiation process of the calling class. This attribute is a Validation::Class::Listing object containing coderef objects and CANNOT be overridden.
π configuration π
The configuration attribute provides the default configuration profile. This attribute is a Validation::Class::Configuration object and CANNOT be overridden.
π directives π
The directives attribute provides access to defined directive objects. This attribute is a Validation::Class::Mapping object containing hashrefs and CANNOT be overridden.
π documents π
The documents attribute provides access to defined document models. This attribute is a Validation::Class::Mapping object and CANNOT be overridden.
π errors π
The errors attribute provides access to class-level error messages. This attribute is a Validation::Class::Errors object, may contain error messages and CANNOT be overridden.
π events π
The events attribute provides access to validation events and the directives that subscribe to them. This attribute is a Validation::Class::Mapping object and CANNOT be overridden.
π fields π
The fields attribute provides access to defined fields objects. This attribute is a Validation::Class::Fields object containing Validation::Class::Field objects and CANNOT be overridden.
π filtering π
The filtering attribute (by default set to 'pre') controls when incoming data is filtered. Setting this attribute to 'post' will defer filtering until after validation occurs which allows any errors messages to report errors based on the unaltered data. Alternatively, setting the filtering attribute to 'off' will bypass all filtering unless explicitly defined at the field-level.
π filters π
The filters attribute provides access to defined filters objects. This attribute is a Validation::Class::Mapping object containing code references and CANNOT be overridden.
π ignore_failure π
The ignore_failure boolean determines whether your application will live or die upon failing to validate a self-validating method defined using the method keyword. This is on (1) by default, method validation failures will set errors and can be determined by checking the error stack using one of the error message methods. If turned off, the application will die and confess on failure.
π ignore_intervention π
The ignore_intervention boolean determines whether validation will short-circuit if required fields are not present. This is off (0) by default; The logic behind this decision is that, for example, in the case of a required field, if the field was not submitted but was required, there is no need to perform additional validation. This is a type-of short-circuiting which reduces validation overhead. If you would like to emit all applicable validation errors you can enable this option.
π ignore_unknown π
The ignore_unknown boolean determines whether your application will live or die upon encountering unregistered field directives during validation. This is off (0) by default, attempts to validate unknown fields WILL cause the program to die.
π messages π
The messages attribute provides access to class-level error message overrides. This attribute is a Validation::Class::Mapping object containing scalar values.
π methods π
The methods attribute provides access to self-validating code references. This attribute is a Validation::Class::Mapping object containing code references.
π mixins π
The mixins attribute provides access to field templates. This attribute is a Validation::Class::Mapping object and CANNOT be overridden.
Also, lowkey: The package attribute contains the namespace of the instance object currently using this module.
π params π
The params attribute provides access to input parameters. This attribute is a Validation::Class::Mapping object and CANNOT be overridden.
π profiles π
The profiles attribute provides access to validation profile. This attribute is a Validation::Class::Mapping object containing hash references and CANNOT be overridden.
π queued π
The queued attribute returns an arrayref of field names for validation and CANNOT be overridden. It represents a list of field names stored to be used in validation later. If the queued attribute contains a list, you can omit arguments to the validate method.
π report_failure π
The report_failure boolean determines whether your application will report self-validating method failures as class-level errors. This is off (0) by default, if turned on, an error messages will be generated and set at the class-level specifying the method which failed in addition to the existing messages.
π report_unknown π
The report_unknown boolean determines whether your application will report unregistered fields as class-level errors upon encountering unregistered field directives during validation. This is off (0) by default, attempts to validate unknown fields will NOT be registered as class-level variables.
π settings π
The settings attribute provides access to settings specific to the associated class, not to be confused with settings which exist in the prototype's configuration. This attribute is a Validation::Class::Mapping object and CANNOT be overridden.
π validated π
The validated attribute simply denotes whether the validation routine has been executed since the last normalization process (which occurs at instantiation and before validation). It's values will either be 0 (not validated), 1 (validated with errors), or 2 (validated without errors). You can simply check this attribute for truth when you need to know if validation has occurred.
β¨ METHODS β¨
π
apply_filters π
The apply_filters method can be used to run the currently defined parameters through the filters defined in their matching fields.
$self = $self->apply_filters;
# apply filters to fields where filtering is set to 'post' filtering
$self = $self->apply_filters('post');
π
class π
This method instantiated and returns the validation class specified , existing parameters and configuration options are passed to the constructor of the validation class (including the stash object). You can prevent/override arguments from being copied to the new class object by supplying the them as arguments to this method.
The class method is also quite handy in that it will detect parameters that are prefixed with the name of the class being fetched, and automatically create aliases on the matching rules (if any) to allow validation to occur seamlessly.
package Class;
use Validation::Class;
load classes => 1; # load child classes e.g. Class::*
package main;
my $input = Class->new(params => $params);
my $child1 = $input->class('Child'); # loads Class::Child;
my $child2 = $input->class('StepChild'); # loads Class::StepChild;
my $child3 = $input->class('child'); # loads Class::Child;
my $child4 = $input->class('step_child'); # loads Class::StepChild;
# intelligently detecting and mapping parameters to child class
my $params = {
'my.name' => 'Guy Friday',
'child.name' => 'Guy Friday Jr.'
};
$input->class('child'); # child field *name* mapped to param *child.name*
# without copying params from class
my $child = $input->class('child', params => {});
1;
π
clear_queue π
The clear_queue method resets the queue container, see the queue method for more information on queuing fields to be validated. The clear_queue method has yet another useful behavior in that it can assign the values of the queued parameters to the list it is passed, where the values are assigned in the same order queued.
my $self = Class->new(params => $params);
$self->queue(qw(name +email));
# ... additional logic
$self->queue(qw(+login +password));
if ($self->validate) {
$self->clear_queue(my($name, $email));
print "Name is $name and email is $email";
}
π
clone_field π
The clone_field method is used to create new fields (rules) from existing fields on-the-fly. This is useful when you have a variable number of parameters being validated that can share existing validation rules. Please note that cloning a field does not include copying and/or processing of any mixins on the original field to the cloned field, if desired, this must be done manually.
package Class;
use Validation::Class;
field 'phone' => {
label => 'Your Phone',
required => 1
};
package main;
my $self = Class->new(params => $params);
# clone phone rule at run-time to validate dynamically created parameters
$self->clone_field('phone', 'phone2', { label => 'Phone A', required => 0 });
$self->clone_field('phone', 'phone3', { label => 'Phone B', required => 0 });
$self->clone_field('phone', 'phone4', { label => 'Phone C', required => 0 });
$self->validate(qw/phone phone2 phone3 phone4/);
1;
π
does π
The does method is used to determine whether the current prototype is composed using the role specified. Return true if so, false if not.
package Class;
use Validation::Class;
set role => 'Class::Root';
package main;
my $self = Class->new(params => $params);
return 1 if $self->proto->does('Class::Root');
π
error_count π
The error_count method returns the total number of errors set at both the class and field level.
my $count = $self->error_count;
π
error_fields π
The error_fields method returns a hashref containing the names of fields which failed validation and an arrayref of error messages.
unless ($self->validate) {
my $failed = $self->error_fields;
}
my $suspects = $self->error_fields('field2', 'field3');
π
errors_to_string π
The errors_to_string method stringifies the all error objects on both the class and fields using the specified delimiter (defaulting to comma-space (", ")).
return $self->errors_to_string("\n");
return $self->errors_to_string(undef, sub{ ucfirst lc shift });
unless ($self->validate) {
return $self->errors_to_string;
}
get_errors π
okay so get_errors hands you back a list of all the errors β class-level AND field-level, all mushed together. iconic.
# returns all errors
my @errors = $self->get_errors;
# filter errors by fields whose name starts with critical
my @critical = $self->get_errors(qr/^critical/i);
# return errors for field_a and field_b specifically
my @specific_field_errors = $self->get_errors('field_a', 'field_b');
get_fields π
get_fields returns the list of Validation::Class::Field objects for whatever fields you ask for β and if you pass no arguments at all it just returns an empty list, no drama. And bestie, if a field doesn't match the name you specified? You get back undefined. periodt.
my ($a, $b) = $self->get_fields('field_a', 'field_b');
get_hash β¨
get_hash gives you a hashref with every field and its absolute value (which is like⦠the default value, or the matching parameter value, whichever applies). And if a field has no absolute value? Its value is just undefined. that's it, that's the vibe.
my $hash = $self->get_hash;
get_params π¦
get_params returns the values of the parameters you name β as a list, in the exact order you asked for them. And if you pass no parameter names, it gives you back a list of key/value pairs instead. slay.
if ($self->validate) {
my ($name) = $self->get_params('name');
my ($name, $email, $login, $password) =
$self->get_params(qw/name email login password/);
# you should note that if the params don't exist they will return
# undef meaning you should check that it is defined before doing any
# comparison checking as doing so would generate an error, e.g.
if (defined $name) {
if ($name eq '') {
print 'name parameter was passed but was empty';
}
}
else {
print 'name parameter was never submitted';
}
}
# alternatively ...
my $params = $self->get_params; # return hashref of parameters
print $params->{name};
lowkey important: if the params don't exist they come back asundef, so checkdefinedfirst before you go comparing anything β otherwise you're generating an error, no cap. π
get_values πΈ
get_values returns the absolute value for a given field. It runs some very specific internal logic to figure out what value that field actually has based on a set of internal conditions. This method always returns a list, and field names that don't exist come back as undefined. bestie behavior honestly.
my ($value) = $self->get_values('field_name');
# equivalent to
my $param = $self->params->get('field_name');
my $field = $self->fields->get('field_name');
my $value;
if ($field->{readonly}) {
$value = $field->{default} || undef;
}
else {
$value = $field->{value} || $param;
}
is_valid π
is_valid returns a boolean β true if the last validation attempt ate and succeeded, false if it didn't. And how does it know? It checks for errors at both the class level and the field level. the way it justβ¦ knows. π
return "OK" if $self->is_valid;
normalize π
normalize runs a whole set of routines that condition the environment, filtering any parameters hanging around whose matching field has its filtering directive set to 'pre'. And guess what β it runs automatically at instantiation, and then again right before every single validation event. it's giving self-sufficient.
$self->normalize;
param π
param gets/sets a single parameter by name. It returns the value assigned, or undefined if that parameter doesn't exist. simple. clean. iconic.
my $value = $self->param('name');
$self->param($name => $value);
plugin π§
plugin returns an instantiated plugin object, and it passes the current prototype object into it. β¨
Note: This functionality is somewhat experimental. (soβ¦ proceed with main character energy but also caution, bestie π)
package Class;
use Validation::Class;
package main;
my $input = Class->new(params => $params);
my $formatter = $input->plugin('telephone_format');
# ... returns a Validation::Class::Plugin::TelephoneFormat object
queue π―
queue is a convenience method made specifically to append the queued attribute, which lets you queue fields up to be validated. It also lets you set fields that must always be validated. obsessed.
$self->queue(qw/name login/);
$self->queue(qw/email email2/) if $input->param('change_email');
$self->queue(qw/login login2/) if $input->param('change_login');
reset π«§
reset clears all errors, fields and queued field names β both at the class level and at the individual field level. factory reset but make it cute.
$self->reset();
reset_errors π
reset_errors clears all errors, both at the class level and the individual field level. And it's called automatically every single time the validate() method gets triggered. so you literally never have to think about it.
$self->reset_errors();
reset_fields β
reset_fields sets special default directives and clears all errors and field values β class level and individual field level both. This one runs automatically at instantiation. π
$self->reset_fields();
reset_params π
reset_params is the one responsible for completely removing any existing parameters and then adding the ones you specified. It returns the class object. It takes a list of key/value pairs, or a single hashref. your call, bestie.
$self->reset_params($new_params);
set_errors π
set_errors pushes its arguments (the error messages) onto the class-level error stack, and returns a count of class-level errors. giving receipts.
my $count = $self->set_errors('...', '...');
set_fields π
set_fields is responsible for setting/overriding registered fields. It returns the class object. It takes a list of key/value pairs, or a single hashref β where the key should be a valid field name and the value should be a hashref that is a valid field configuration object.
$self->set_fields($name => $config); # accepts hashref also
set_params π¦
set_params is responsible for setting/replacing parameters. It returns the class object. It takes a list of key/value pairs, or a single hashref whose keys should match field names and whose values should be a scalar or an arrayref of scalars.
$self->set_params($name => $value); # accepts a hashref also
set_value β¨
set_value assigns a value to the specified field's parameter β unless the field is readonly. It returns the class object.
$self->set_values($name => $value);
stash π§Ί
stash gives you a container for context/instance specific info. It's especially useful when your custom validation routines need insight into context/instance specific operations. like a little purse you keep your important stuff in. π«Ά
package MyApp::Person;
use Validation::Class;
field 'email' => {
validation => sub {
my ($self) = @_;
my $db = $self->stash('database');
return 0 unless $db;
return $db->find(...) ? 0 : 1 ; # email exists
}
};
package main;
# store the database object for use in email validation
$self->stash(database => $database_object);
validate π
The validate method (or has_valid, or validates) returns true/false depending on whether all the specified fields passed their validation checks.
bestie, listen: if this method gets called without any parameters, the list of fields to be validated will be assumed/deduced, which makes the execution strategy conditional β and that might not be what you want. be intentional. π
use MyApp::Person;
my $input = MyApp::Person->new(params => $params);
# validate specific fields
unless ($input->validate('login','password')){
return $input->errors_to_string;
}
# validate fields based on a regex pattern
unless ($input->validate(qr/^setting(\d+)?/)){
return $input->errors_to_string;
}
# validate existing parameters
# however, if no parameters exist, ...
# validate all fields, which will return true unless a field exists
# with a required directive
unless ($input->validate){
return $input->errors_to_string;
}
# validate all fields period, obviously
unless ($input->validate($input->fields->keys)){
return $input->errors_to_string;
}
# implicitly validate parameters which don't explicitly match a field
my $parameter_map = {
user => 'login',
pass => 'password'
};
unless ($input->validate($parameter_map)){
return $input->errors_to_string;
}
Another cool trick validate() can pull off: it can temporarily change whether a field is required or not during validation. this is often called the toggle function and it is genuinely so useful. β¨
This matters when you've defined a field as required (or not) and you want to flip that per validation. You do it by calling validate() with a list of fields to validate and prefixing the target fields with a plus or minus respectively, like so:
use MyApp::Person;
my $input = MyApp::Person->new(params => $params);
# validate specific fields, force name, email and phone to be required
# regardless of the field directives ... and force the age, sex
# and birthday to be optional
my @spec = qw(+name +email +phone -age -sex -birthday);
unless ($input->validate(@spec)){
return $input->errors_to_string;
}
validate_document π
The validate_document method (or document_validates) validates the specified hierarchical data against the specified document declaration. This is extremely valuable for validating serialized messages passed between machines. π₯
It needs two arguments: the name of the document declaration to use, and the data to validate β which should be submitted as a hashref. like this:
my $boolean = $self->validate_document(foobar => $data);
Also, you can submit options as a hashref to further control the validation process:
# the prune option removes non-matching parameters (nodes)
my $boolean = $self->validate_document(foobar => $data, { prune => 1 });
And to support validation of ad-hoc specs, you can pass this method two hashrefs β the first being the document notation schema, and the second being the hierarchical data you want to validate. versatile queen. π
validate_method π―
The validate_method method (or method_validates) figures out whether a self-validating method will be successful. How? By validating the method's input specification. π¦
This is useful when it's advantageous to know in advance whether a self-validating method will pass or fail β it effectively lets you use the method's input specification as a validation profile. iconic foresight, honestly.
if ($self->validate_method('password_change')) {
# password_change will pass validation
if ($self->password_change) {
# password_change executed
}
}
okay so the vibe here is: you check first, then you act. validate_method says "yeah bestie, password_change is valid" and only then does $self->password_change actually fire. Checking before doing? that's the energy. π
πΈ validate_profile πΈ
The validate_profile method (or its lil nickname profile_validates) runs a stored validation profile for you. π«Ά
Here's the tea β:
- It needs a profile name β that's the one thing it cannot live without.
- You can also pass it extra parameters, and those get forwarded straight into the profile routine in the order received. So the order you give them is the order they show up. No shuffling, no remixing. β¨
Watch it in action:
unless ($self->validate_profile('password_change')) {
print $self->errors_to_string;
}
See that? If the profile doesn't pass, it prints the errors so you actually know what went wrong. Communicative queen. π
And with extra params sliding in:
unless ($self->validate_profile('email_change', $dbi_handle)) {
print $self->errors_to_string;
}
There, $dbi_handle gets forwarded into the email_change profile routine. Extra baggage but make it useful. π
fr fr, ifvalidate_profilecomes back false, hit uperrors_to_stringβ that's where the receipts live. π§Ύ
π AUTHOR π
Al Newkirk <anewkirk@ana.io>
π¦ COPYRIGHT AND LICENSE π¦
This software is copyright (c) 2011 by Al Newkirk.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
and that's a wrap on the whole page, bestie. π This lil doc drop came to you via perl v5.36.0, dated 2023-06-11 β iconic, timeless, ate. Now go validate something and slay. πβ¨π
π¦ where this page comes from
- debian trixie: libvalidation-class-perl 7.900059-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: libvalidation-class-perl 7.900059-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libvalidation-class-perl 7.900059-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libvalidation-class-perl 7.900059-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms