The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Validation::Class::Prototype - Prototype and Data Validation Engine for Validation::Class

VERSION

version 7.58

SYNOPSIS

    package MyApp::User;
    
    use Validation::Class;
    
    # import other class config, etc
    
    set {
        # ...
    };
    
    # a mixin template
    
    mxn 'basic'  => {
        required   => 1
    };
    
    # a validation rule
    
    fld 'login'  => {
        label      => 'User Login',
        error      => 'Login invalid.',
        mixin      => 'basic',
        
        validation => sub {
        
            my ($self, $this_field, $all_params) = @_;
        
            return $this_field->value eq 'admin' ? 1 : 0;
        
        }
        
    };
    
    # a validation rule
    
    fld 'password'  => {
        label         => 'User Password',
        error         => 'Password invalid.',
        mixin         => 'basic',
        
        validation    => sub {
        
            my ($self, $this_field, $all_params) = @_;
        
            return $this_field->value eq 'pass' ? 1 : 0;
        
        }
        
    };
    
    # a validation profile
    
    pro 'registration'  => sub {
        
        my ($self, @args) = @_;
        
        return $self->validate(qw(+name +email -login +password))
        
    };
    
    # an auto-validating method
    
    mth 'register'  => {
        
        input => 'registration',
        using => sub {
            
            my ($self, @args) = shift;
            
            # ... do something
            
        }
        
    };
    
    1;

DESCRIPTION

Validation::Class::Prototype provides the data validation schema and routines for all Validation::Class based classes. This class inherits from Validation::Class::Base.

ATTRIBUTES

directives

The directives attribute returns a hashref of all defined directives.

    my $directives = $self->directives();
    ...

errors

The errors attribute provides error handling functionality and CANNOT be overridden. This attribute is a Validation::Class::Errors object.

    my $errors = $self->errors();
    ...

fields

The fields attribute provides field handling functionality and CANNOT be overridden. This attribute is a Validation::Class::Fields object.

    my $fields = $self->fields();
    ...

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 '' or undef will bypass all filtering unless explicitly defined at the field-level.

    my $filtering = $self->filtering('post');
    
    $self->validate();
    ...

filters

The filters attribute returns a hashref of pre-defined filter definitions.

    my $filters = $self->filters();
    ...

hash_inflator

The hash_inflator attribute determines how the hash serializer (inflation/deflation) behaves. The value must be a hashref of "OPTIONS" in Hash::Flatten options. Purely for the sake of consistency, you can use lowercase keys (with underscores) which will be converted to camel-cased keys before passed to the serializer.

    my $self = MyApp::Validation->new(hash_inflator => {
        hash_delimiter => '/',
        array_delimiter => '//'
    });
    
    ...
    
    # then, hereinafter referred to as 
    
    $self->hash_inflator->{HashDelimiter} = '/';
    $self->hash_inflator->{ArrayDelimiter} = '//';

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.

    my $ignoring = $self->ignore_failure(1);
    ...

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.

    my $ignoring = $self->ignore_unknown(1);
    ...

methods

The methods attribute returns a hashref of self-validating method definitions.

    my $methods = $self->methods(); # definitions are hashrefs
    ...

mixins

The mixins attribute returns a hashref of defined validation templates.

    my $mixins = $self->mixins();
    ...

params

The params attribute provides parameter handling functionality and CANNOT be overridden. This attribute is a Validation::Class::Params object.

    my $params = $self->params();
    ...

plugins

The plugins attribute returns a hashref of loaded plugins.

    my $plugins = $self->plugins();
    ...

profiles

The profiles attribute returns a hashref of validation profiles.

    my $profiles = $self->profiles();
    ...

queued

The queued attribute returns an arrayref of field names for (auto) validation. 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.

    my $queued = $self->queued([qw/.../]);
    ...

relatives

The relatives attribute returns a hashref of short-name/class-name pairs of loaded child classes.

    my $relatives = $self->relatives();
    ...

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.

    my $reporting = $self->report_failure(0);
    ...

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.

    my $reporting = $self->report_unknown(1);
    ...

METHODS

apply_filters

The apply_filters method (usually called automatically based on the filtering attribute) 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 labeled as "don't filter automatically" (post)
    $self = $self->apply_filters('post'); 

class

The class method returns a new initialize validation class related to the namespace of the calling class, the relative class would've been loaded via the "load" keyword.

Existing parameters and configuration options are passed to the relative class' constructor (including the stash). All attributes can be easily overwritten using the attribute's accessors on the relative class.

Also, you may 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 adjust the matching rule (if any) to allow validation to occur.

    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;
    
    # use any non-alphanumeric character or underscore as the namespace delimiter
    
    my $child5  = $input->class('step/child'); # loads Class::Step::Child;
    my $child5a = $input->class('step:child'); # loads Class::Step::Child;
    my $child5b = $input->class('step.child'); # loads Class::Step::Child;
    my $child5c = $input->class('step-child'); # loads Class::Step::Child;
    
    my $child6  = $input->class('CHILD');      # loads Class::CHILD;
    
    # intelligently detecting and map params 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 => {});
    
    # alternate syntax
    
    my $child = $input->class(name => '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));
    
    ...
    
    $self->queue(qw(+login +password));
    
    if ($self->validate) {
        
        $self->clear_queue(my($name, $email));
        
        print "Name is $name";
        
    }

clone

The clone 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.

    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('phone', 'phone2', { label => 'Other Phone', required => 0 });
    $self->clone('phone', 'phone3', { label => 'Third Phone', required => 0 });
    $self->clone('phone', 'phone4', { label => 'Forth Phone', required => 0 });
    
    $self->validate(qw/phone phone2 phone3 phone4/);
    
    1;

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;
    
    }

flatten_params

The flatten_params method accepts a single hashref and will return the serialized version based on the the default or custom configuration of the hash serializer Hash::Flatten as configured via the hash_inflator() attribute.

    my $params = {
        
        user => {
            login => 'member',
            password => 'abc123456'
        }
        
    };
    
    my $serialized_params = $self->flatten_params($params);

get_errors

The get_errors method returns a list of combined class-and-field-level errors.

    my @errors = $self->get_errors; # returns list
    
    my @critical = $self->get_errors(qr/^critical:/i); # filter errors
    
    my @specific_field_errors = $self->get_errors('field_a', 'field_b');

get_fields

The get_fields method returns the list of references to the specified fields. Returns undef if no arguments are passed. This method is likely to be used more internally than externally.

    my ($this, $that) = $self->get_fields('this', 'that');

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. Note, this method always returns exploded/unflattened parameters.

    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_value

The get_value method returns the absolute value (hardcoded, default or parameter specified) 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 otherwise returns undefined.

    my $value = $self->get_value('field_name');

normalize

The normalize method executes a set of routines that reset the parameter environment filtering any parameters present. 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 the instantiated plugin object attached to the current class.

    package Class;
    
    use Validation::Class;
    
    load plugin => ['TelephoneFormat'];
    load plugin => ['+Class::Plugin::Form::Elements'];
    
    package main;
    
    my $input = Class->new(params => $params);
    
    # get object for Validation::Class::Plugin::TelephoneFormat;
    
    my $plugin = $input->plugin('telephone_format');
    
    # use any non-alphanumeric character or underscore as the namespace delimiter
    # get object for Class::Plugin::Form::Elements;
    # note the leading character/delimiter
    
    my $plugin = $input->plugin(':class:plugin:form:elements'); 
    
    # same as $input->proto->plugins->{'Class::Plugin::Form::Elements'};
    
    my $plugin = $input->plugin('Class::Plugin::Form::Elements');

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_confirm/) if $input->param('chg_email');
    $self->queue(qw/password_confirm/) if $input->param('chg_pass');

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 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 = $self->reset_params($new_params); # accepts list also

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 = $self->set_fields($name => $config); # accepts hashref also

set_method

The set_method method conveniently creates a method on the calling class, this method is primarily intended to be used during instantiation of a plugin during instantiation of the validation class.

    my $sub = $self->set_method(do_something => sub { ... });

Additionally, method names are flattened, e.g. ThisFunction will be converted to this_function for convenience and consistency.

set_params

The set_params method is responsible for setting/replacing parameters while ensuring that previously serialized parameters are taken into account. This method returns the class object. This method takes a list of key/value pairs or a single hashref whose key should match a field's name and whose value should be a scalar or arrayref.

    $self = $self->set_params($name => $value); # accepts hashref also

set_value

The set_value method assigns a value to the specified field's parameter unless the field is readonly.

    $self = $self->set_value($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::Validation;
    
    use Validation::Class;
    
    fld 'email' => {
        
        validation => sub {
            
            my ($self) = @_;
            
            my $db = $self->stash('database');
            
            return $db->find(...) ? 0 : 1 ; # email exists
            
        }
        
    };
    
    package main;
    
    $self->stash( { database => $dbix_object } );
    $self->stash( database => $dbix_object );
    
    ...

unflatten_params

The unflatten_params method accepts a single *flat* hashref and will return the expanded version based on the the default or custom configuration of the hash serializer Hash::Flatten as configured via the hash_inflator() attribute.

    my $params = {
        'user.login' => 'member',
        'user.password' => 'abc123456'
    };
    
    $params = $self->unflatten_params($params);
        
    print $params->{user}->{login};

validate

The validate method returns true/false depending on whether all specified fields passed validation checks.

    use MyApp::Validation;
    
    my $input = MyApp::Validation->new(params => $params);
    
    # validate specific fields
    unless ($input->validate('field1','field2')){
        return $input->errors_to_string;
    }
    
    # validate fields based on a regex pattern
    unless ($input->validate(qr/^field(\d+)?/)){
        return $input->errors_to_string;
    }
    
    # validate existing parameters, if no parameters exist,
    # validate all fields ... which will return true unless field(s) exist
    # with a required directive
    unless ($input->validate()){
        return $input->errors_to_string;
    }
    
    # validate all fields period, obviously
    unless ($input->validate(keys %{$input->fields})){
        return $input->errors_to_string;
    }
    
    # validate specific parameters (by name) after mapping them to other fields
    my $parameter_map = {
        user => 'hey_im_not_named_login',
        pass => 'password_is_that_really_you'
    };
    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 run-time. This functionality is often referred to as the *toggle* function.

This method is important when you define a field (or two or three) 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 as follows:

    use MyApp::Validation;
    
    my $input = MyApp::Validation->new(params => $params);
    
    # validate specific fields, force name, email and phone to be required
    # regardless of the field definitions 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_profile

The validate_profile method 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;
        
    }

DIRECTIVES

    package MyApp::Validation;
    
    use Validation::Class;
    
    # a validation template
    
    mixin '...'  => {
        # mixin directives here
        ...
    };
    
    # a validation rule
    
    field '...'  => {
        # field directives here
        ...
    };
    
    1;

When building a validation class, the first encountered and arguably two most important keyword functions are field() and mixin(), which are used to declare their respective properties. A mixin() declares a validation template where its properties are intended to be copied within field() declarations which declares validation rules, filters and other properties.

Both the field() and mixin() declarations/functions require two parameters, the first being a name, used to identify the declaration and to be matched against incoming input parameters and the second being a hashref of key/value pairs. The key(s) within a declaration are commonly referred to as directives.

The following is a list of default directives which can be used in field/mixin declarations:

alias

The alias directive is useful when many different parameters with different names can be validated using a single rule. E.g. The paging parameters in a webapp may take on different names but require the same validation.

    # the alias directive
    field 'pager'  => {
        alias => ['page_user_list', 'page_other_list']
        ...
    };

default

The default directive is used as a default value for a field to be used when a matching parameter is not present. Optionally, the default directive can be a coderef allowing the default value to be set on request.

    # the default directive
    field 'quantity'  => {
        default => 1,
        ...
    };
    
    # the default directive as a coderef
    field 'quantity'  => {
        default => sub {
            return DB::Settings->default_quantity
        }
    };

error/errors

The error/errors directive is used to replace the system generated error messages when a particular field doesn't validate. If a field fails multiple directives, multiple errors will be generated for the same field. This may not be desirable, the error directive overrides this behavior and only the specified error is registered and displayed.

    # the error(s) directive
    field 'foobar'  => {
        errors => 'Foobar failed processing, Wtf?',
        ...
    };

filtering

The filtering directive is used to control when field filters are applied. The default recognized values are pre/post. A value of 'pre' instructs the validation class to apply the field's filters at instantiation and before validation whereas a value of 'post' instructs the validation class to apply the field's filters after validation. Alternatively, a value of undef or '' will bypass filtering altogether.

    # the filtering directive
    field 'foobar'  => {
        filtering => 'post',
        ...
    };

label

The label directive is used as a user-friendly reference when the field name is a serialized hash key or just plain ugly.

    # the label directive
    field 'hashref.foo.bar'  => {
        label => 'Foo Bar',
        ...
    };

mixin

The mixin directive is used to create a template of directives to be applied to other fields.

    mixin 'ID' => {
        required => 1,
        min_length => 1,
        max_length => 11
    };

    # the mixin directive
    field 'user.id'  => {
        mixin => 'ID',
        ...
    };

mixin_field

The mixin directive is used to copy all directives from an existing field except for the name, label, and validation directives.

    # the mixin_field directive
    field 'foobar'  => {
        label => 'Foo Bar',
        required => 1
    };
    
    field 'barbaz'  => {
        mixin_field => 'foobar',
        label => 'Bar Baz',
        ...
    };

name

The name directive is used *internally* and cannot be changed.

    # the name directive
    field 'thename'  => {
        ...
    };

readonly

The readonly directive is used to symbolize a field whose parameter value should not be honored and if encountered, deleted. Unlike the read-only attribute options in other object systems, setting this will not cause you program to die and in-fact, an experience programmer can selectively bypass this constraint.

    # the readonly directive
    field 'thename'  => {
        readonly => 1,
        ...
    };

value

The value directive is used internally to store the field's matching parameter's value. This value can be set in the definition but SHOULD NOT BE used as a default value unless you're sure no parameter will overwrite it during run-time. If you need to set a default value, see the default directive.

    # the value directive
    field 'quantity'  => {
        value => 1,
        ...
    };

DIRECTIVES (FILTERS)

The filters directive is used to correct, alter and/or format the values of the matching input parameter. Note: Filtering is applied before validation. The filter directive can have multiple filters (even a coderef) in the form of an arrayref of values.

    # the filter(s) directive
    field 'text'  => {
        filters => [qw/trim strip/ => sub {
            $_[0] =~ s/\D//g;
        }],
        ...
    };

The following is a list of default filters that may be used with the filter directive:

alpha

The alpha filter removes all non-Alphabetic characters from the field's value.

    field 'foobar'  => {
        filters => 'alpha',
    };

alphanumeric

The alpha filter removes all non-Alphabetic and non-Numeric characters from the field's value.

    field 'foobar'  => {
        filters => 'alphanumeric',
    };

capitalize

The capitalize filter attempts to capitalize the first word in each sentence, where sentences are separated by a period and space, within the field's value.

    field 'foobar'  => {
        filters => 'capitalize',
    };

decimal

The decimal filter removes all non-decimal-based characters from the field's value. Allows only: decimal, comma, and numbers.

    field 'foobar'  => {
        filters => 'decimal',
    };

lowercase

The lowercase filter converts the field's value to lowercase.

    field 'foobar'  => {
        filters => 'lowercase',
    };

numeric

The numeric filter removes all non-numeric characters from the field's value.

    field 'foobar'  => {
        filters => 'numeric',
    };

strip

As with the trim filter the strip filter removes leading and trailing whitespaces from the field's value and additionally removes multiple whitespaces from between the values characters.

    field 'foobar'  => {
        filters => 'strip',
    };

titlecase

The titlecase filter converts the field's value to titlecase by capitalizing the first letter of each word.

    field 'foobar'  => {
        filters => 'titlecase',
    };

trim

The trim filter removes leading and trailing whitespace from the field's value.

    field 'foobar'  => {
        filters => 'trim',
    };

uppercase

The uppercase filter converts the field's value to uppercase.

    field 'foobar'  => {
        filters => 'uppercase',
    };

DIRECTIVES (VALIDATORS)

    package MyApp::Validation;
    
    use Validation::Class;
    
    # a validation rule with validator directives
    field 'telephone_number'  => {
        length => 14,
        pattern => '(###) ###-####',
        ...
    };
    
    1;

Validator directives are special directives with associated validation code that is used to validate common use cases such as "checking the length of a parameter", etc.

Please note that a directive's value can be either a scalar or arrayref, most directives take a scalar value though some have the ability to take an arrayref or parse a delimited list. There is no official documentation as to which directives can accept lists of values although it will typically be evident.

    E.g. (a directive with a list of values)
    
    {
        directive => [qw(1 2 3)],
        directive => ['1', '2', '3'],
        directive => '1, 2, 3',
        directive => '1-2-3',
        directive => '1,2,3',
    }

The following is a list of the default validators which can be used in field/mixin declarations:

between

    # the between directive
    field 'foobar'  => {
        between => '1-5',
        ...
    };

depends_on

    # the depends_on directive
    field 'change_password'  => {
        depends_on => ['password', 'password_confirm'],
        ...
    };

length

    # the length directive
    field 'foobar'  => {
        length => 20,
        ...
    };

matches

    # the matches directive
    field 'this_field'  => {
        matches => 'another_field',
        ...
    };

max_alpha

    # the max_alpha directive
    field 'password'  => {
        max_alpha => 30,
        ...
    };

max_digits

    # the max_digits directive
    field 'password'  => {
        max_digits => 5,
        ...
    };

max_length

    # the max_length directive
    field 'foobar'  => {
        max_length => '...',
        ...
    };

max_sum

    # the max_sum directive
    field 'vacation_days'  => {
        max_sum => 5,
        ...
    };

max_symbols

    # the max_symbols directive
    field 'password'  => {
        max_symbols => 1,
        ...
    };

min_alpha

    # the min_alpha directive
    field 'password'  => {
        min_alpha => 2,
        ...
    };

min_digits

    # the min_digits directive
    field 'password'  => {
        min_digits => 1,
        ...
    };

min_length

    # the min_length directive
    field 'foobar'  => {
        min_length => '...',
        ...
    };

min_sum

    # the min_sum directive
    field 'vacation_days'  => {
        min_sum => 0,
        ...
    };

min_symbols

    # the min_symbols directive
    field 'password'  => {
        min_symbols => 0,
        ...
    };

options

    # the options directive
    field 'status'  => {
        options => 'Active, Inactive',
        ...
    };

pattern

    # the pattern directive
    field 'telephone'  => {
        # simple pattern
        pattern => '### ###-####',
        ...
    };
    
    field 'country_code'  => {
        # simple pattern
        pattern => 'XX',
        filter  => 'uppercase'
        ...
    };
    
    field 'complex'  => {
        # regex pattern
        pattern => qr/[0-9]+\,\s\.\.\./,
        ...
    };

required

The required directive is an important directive but can be misunderstood. The required directive is used to ensure the submitted parameter exists and has a value. If the parameter is never submitted, the directive is effectively skipped. This directive can be thought of as the "must-have-a-value-if-exists" directive.

    # the required directive
    field 'foobar'  => {
        required => 1,
        ...
    };
    
    # pass
    my $rules = MyApp::Validation->new(params => {   });
    $rules->validate(); #validate everything
    
    # fail
    my $rules = MyApp::Validation->new(params => { foobar => '' });
    $rules->validate(); #validate everything
    
    # fail
    my $rules = MyApp::Validation->new(params => {  });
    $rules->validate('foobar');
    
    # fail
    my $rules = MyApp::Validation->new(params => { foobar => '' });
    $rules->validate('foobar');
    
    # pass
    my $rules = MyApp::Validation->new(params => {  foobar => 'Nice' });
    $rules->validate('foobar');

See the toggle functionality within the validate() method. This method allows you to temporarily alter whether a field is required or not.

validation

The validation directive is a coderef used add additional custom validation to the field. The coderef must return true (to pass) or false (to fail). Custom error messages can be set from within the coderef so make sure they are set based on appropriate logic as the registration of error message are not contingent on the success or failure of the routine.

    # the validation directive
    field 'login'  => {
        
        validation => sub {
        
            my ($self, $this_field, $all_params) = @_;
        
            return 0 unless $this_field->value;
            return $this_field->value eq 'admin' ? 1 : 0;
        
        },
        
    };

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.