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.

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

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;

    }

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.