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
The get_errors method returns a list of combined class-and-field-level errors.
# 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
The get_fields method returns the list of Validation::Class::Field objects for specific fields and
returns an empty list if no arguments are passed. If a field does not match the name specified it will
return undefined.
my ($a, $b) = $self->get_fields('field_a', 'field_b');
get_hash
The get_hash method returns a hashref consisting of all fields with their absolute values (i.e. default
value or matching parameter value). If a field does not have an absolute value its value will be
undefined.
my $hash = $self->get_hash;
get_params
The get_params method returns the values of the parameters specified (as a list, in the order specified).
This method will return a list of key/value pairs if no parameter names are passed.
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};
get_values
The get_values method returns the absolute value for a given field. This method executes specific logic
which returns the value a field has based on a set of internal conditions. This method always returns a
list, field names that do not exist are returned as undefined.
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
The is_valid method returns a boolean value which is true if the last validation attempt was successful,
and false if it was not (which is determined by looking for errors at the class and field levels).
return "OK" if $self->is_valid;
normalize
The normalize method executes a set of routines that conditions the environment filtering any parameters
present whose matching field has its filtering directive set to 'pre'. This method is executed
automatically at instantiation and again just before each validation event.
$self->normalize;
param
The param method gets/sets a single parameter by name. This method returns the value assigned or
undefined if the parameter does not exist.
my $value = $self->param('name');
$self->param($name => $value);
plugin
The plugin method returns an instantiated plugin object which is passed the current prototype object.
Note: This functionality is somewhat experimental.
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
The queue method is a convenience method used specifically to append the queued attribute allowing you to
*queue* fields to be validated. This method also allows you to set fields that must always be validated.
$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
The reset method clears all errors, fields and queued field names, both at the class and individual field
levels.
$self->reset();
reset_errors
The reset_errors method clears all errors, both at the class and individual field levels. This method is
called automatically every time the validate() method is triggered.
$self->reset_errors();
reset_fields
The reset_fields method set special default directives and clears all errors and field values, both at
the class and individual field levels. This method is executed automatically at instantiation.
$self->reset_fields();
reset_params
The reset_params method is responsible for completely removing any existing parameters and adding those
specified. This method returns the class object. This method takes a list of key/value pairs or a single
hashref.
$self->reset_params($new_params);
set_errors
The set_errors method pushes its arguments (error messages) onto the class-level error stack and returns
a count of class-level errors.
my $count = $self->set_errors('...', '...');
set_fields
The set_fields method is responsible setting/overriding registered fields. This method returns the class
object. This method takes a list of key/value pairs or a single hashref whose key should be a valid field
name and whose value should be a hashref that is a valid field configuration object.
$self->set_fields($name => $config); # accepts hashref also
set_params
The set_params method is responsible for setting/replacing parameters. This method returns the class
object. This method takes a list of key/value pairs or a single hashref whose keys should match field
names and whose value should be a scalar or arrayref of scalars.
$self->set_params($name => $value); # accepts a hashref also
set_value
The set_value method assigns a value to the specified field's parameter unless the field is readonly.
This method returns the class object.
$self->set_values($name => $value);
stash
The stash method provides a container for context/instance specific information. The stash is
particularly useful when custom validation routines require insight into context/instance specific
operations.
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 specified
fields passed validation checks. Please consider, if this method is called without any parameters, the
list of fields to be validated will be assumed/deduced, making the execution strategy conditional, which
may not be what you want.
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 the validate() method can perform is the ability to temporarily alter whether a field
is required or not during validation. This functionality is often referred to as the *toggle* function.
This method is important when you define a field as required or non and want to change that per
validation. This is done by calling the validate() method with a list of fields to be validated and
prefixing the target fields with a plus or minus respectively as follows:
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) is used to validate the specified hierarchical data
against the specified document declaration. This is extremely valuable for validating serialized messages
passed between machines. This method requires two arguments, the name of the document declaration to be
used, and the data to be validated which should be submitted in the form of a hashref. The following is
an example of this technique:
my $boolean = $self->validate_document(foobar => $data);
Additionally, you may submit options in the form of a hashref to further control the validation process.
The following is an example of this technique:
# the prune option removes non-matching parameters (nodes)
my $boolean = $self->validate_document(foobar => $data, { prune => 1 });
Additionally, to support the validation of ad-hoc specifications, you may pass this method two hashrefs,
the first being the document notation schema, and the second being the hierarchical data you wish to
validate.
validate_method
The validate_method method (or method_validates) is used to determine whether a self-validating method
will be successful. It does so by validating the methods input specification. This is useful in
circumstances where it is advantageous to know in-advance whether a self-validating method will pass or
fail. It effectively allows you to use the methods input specification as a validation profile.
if ($self->validate_method('password_change')) {
# password_change will pass validation
if ($self->password_change) {
# password_change executed
}
}
validate_profile
The validate_profile method (or profile_validates) executes a stored validation profile, it requires a
profile name and can be passed additional parameters which get forwarded into the profile routine in the
order received.
unless ($self->validate_profile('password_change')) {
print $self->errors_to_string;
}
unless ($self->validate_profile('email_change', $dbi_handle)) {
print $self->errors_to_string;
}