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

NAME

Validation::Class::Simple - Simple Ad-Hoc Data Validation

VERSION

version 7.900035

SYNOPSIS

    use Validation::Class::Simple;

    # define object specific rules
    my $rules = Validation::Class::Simple->new(
        # define fields on-the-fly
        fields => {
            name  => { required => 1 },
            email => { required => 1 },
            pass  => { required => 1 },
            pass2 => { required => 1, matches => 'pass' },
        }
    );

    # set parameters to be validated
    $rules->params->add($parameters);

    # validate
    unless ($rules->validate) {
        # handle the failures
    }

DESCRIPTION

Validation::Class::Simple is a simple validation module built around the powerful Validation::Class data validation framework.

This module is merely a blank canvas, a clean validation class derived from Validation::Class which has not been pre-configured (e.g. configured via keywords, etc).

It can be useful in an environment where you wouldn't care to create a validation class and instead would simply like to pass rules to a validation engine in an ad-hoc fashion.

QUICKSTART

If you are looking for a data validation module with an even lower learning curve built using the same tenets and principles as Validation::Class which is as simple and even lazier than this module, please review the tested but experimental Validation::Class::Simple::Streamer.

RATIONALE

If you are new to Validation::Class, or would like more information on the underpinnings of this library and how it views and approaches data validation, please review Validation::Class::Whitepaper.

PROXY METHODS

Each instance of Validation::Class::Simple is associated with a *prototype* class which provides the data validation engine and keeps the class namespace free from pollution and collisions, please see Validation::Class::Prototype for more information on specific methods and attributes.

Validation::Class::Simple is injected with a few proxy methods which are basically aliases to the corresponding prototype (engine) class methods, however it is possible to access the prototype directly using the proto/prototype methods.

class

    $self->class;

See "class" in Validation::Class::Prototype for full documentation.

clear_queue

    $self->clear_queue;

See "clear_queue" in Validation::Class::Prototype for full documentation.

error_count

    $self->error_count;

See "error_count" in Validation::Class::Prototype for full documentation.

error_fields

    $self->error_fields;

See "error_fields" in Validation::Class::Prototype for full documentation.

errors

    $self->errors;

See "errors" in Validation::Class::Prototype for full documentation.

head2 errors_to_string

    $self->errors_to_string;

See "errors_to_string" in Validation::Class::Prototype for full documentation.

get_errors

    $self->get_errors;

See "get_errors" in Validation::Class::Prototype for full documentation.

get_fields

    $self->get_fields;

See "get_fields" in Validation::Class::Prototype for full documentation.

get_params

    $self->get_params;

See "get_params" in Validation::Class::Prototype for full documentation.

fields

    $self->fields;

See "fields" in Validation::Class::Prototype for full documentation.

filtering

    $self->filtering;

See "filtering" in Validation::Class::Prototype for full documentation.

ignore_failure

    $self->ignore_failure;

See "ignore_failure" in Validation::Class::Prototype for full documentation.

ignore_unknown

    $self->ignore_unknown;

See "ignore_unknown" in Validation::Class::Prototype for full documentation.

param

    $self->param;

See "param" in Validation::Class::Prototype for full documentation.

params

    $self->params;

See "params" in Validation::Class::Prototype for full documentation.

queue

    $self->queue;

See "queue" in Validation::Class::Prototype for full documentation.

report_failure

    $self->report_failure;

See "report_failure" in Validation::Class::Prototype for full documentation.

report_unknown

    $self->report_unknown;

See "report_unknown" in Validation::Class::Prototype for full documentation.

reset_errors

    $self->reset_errors;

See "reset_errors" in Validation::Class::Prototype for full documentation.

reset_fields

    $self->reset_fields;

See "reset_fields" in Validation::Class::Prototype for full documentation.

reset_params

    $self->reset_params;

See "reset_params" in Validation::Class::Prototype for full documentation.

set_errors

    $self->set_errors;

See "set_errors" in Validation::Class::Prototype for full documentation.

set_fields

    $self->set_fields;

See "set_fields" in Validation::Class::Prototype for full documentation.

set_params

    $self->set_params;

See "set_params" in Validation::Class::Prototype for full documentation.

set_method

    $self->set_method;

See "set_method" in Validation::Class::Prototype for full documentation.

stash

    $self->stash;

See "stash" in Validation::Class::Prototype for full documentation.

validate

    $self->validate;

See "validate" in Validation::Class::Prototype for full documentation.

validate_method

    $self->validate_method;

See "validate_method" in Validation::Class::Prototype for full documentation.

validate_profile

    $self->validate_profile;

See "validate_profile" in Validation::Class::Prototype for full documentation.

GUIDED TOUR

The instructions contained in this documentation are also relevant for configuring any class derived from Validation::Class. The validation logic that follows is not specific to a particular use-case.

Parameter Handling

There are three ways to declare parameters you wish to have validated. The first and most common approach is to supply the target parameters to the validation class constructor:

    use Validation::Simple;

    my $rules = Validation::Simple->new(params => $parameters);

All input parameters are wrapped by the Validation::Class::Params container which provides generic functionality for managing hashes. Additionally you can declare parameters by using the params object directly:

    use Validation::Simple;

    my $rules = Validation::Simple->new;

    $rules->params->clear;

    $rules->params->add(user => 'admin', pass => 's3cret');

    printf "%s parameters were submitted", $rules->params->count;

Finally, any parameter which has corresponding validation rules that has been declared in a validation class derived from Validation::Class will have an accessor which can be used directly or as an argument to the constructor:

    package MyApp::Person;

    use Validation::Class;

    field 'name' => {
        required => 1
    };

    package main;

    my $rules = MyApp::Person->new(name => 'Egon Spangler');

    $rules->name('Egon Spengler');

Validation Rules

Validation::Class comes with a complete standard set of validation rules which allows you to easily describe the constraints and operations that need to be performed per parameter.

Validation rules are referred to as fields, fields are named after the parameters they expect to be matched against. A field is also a hashref whose keys are called directives which correspond with the names of classes in the directives namespace, and whose values are arguments which control how directives carry-out their operations.

    use Validation::Simple;

    my $rules = Validation::Simple->new;

    $rules->fields->clear;

    $rules->fields->add(name => { required => 1, max_length => 255 });

Fields can be specified as an argument to the class constructor, or managed directly using the Validation::Class::Fields container. Every field is wrapped by the Validation::Class::Field container which provides accessors for all core directives. Directives can be found under the directives namespace, e.g. the required directive refers to Validation::Class::Directive::Required. Please see Validation::Class::Directives for a list of all core directives.

Flow Control

A good data validation tool is not simply checking input against constraints, its also providing a means to easily handle different and often complex data input scenarios.

The queue method allows you to designate and defer fields to be validated. It also allows you to set fields that must be validated regardless of what has been passed to the validate method. Additionally it allows you to conditionally specify constraints:

    use Validation::Simple;

    my $rules = Validation::Simple->new;

    $rules->queue('name'); # always validate the name parameter

    $rules->queue('email', 'email2') if $rules->param('change_email');
    $rules->queue('login', 'login2') if $rules->param('change_login');

    # validate name
    # validate email and email confirmation if change_email is true
    # validate login and login confirmation if change_login is true

    $rules->validate('password'); # additionally, validate password
    $rules->clear_queue;          # reset the queue when finished

Akin to the queue method is the stash method. At-times it is necessary to break out of the box in order to design constraints that fit your particular use-case. The stash method allows you to share arbitrary objects with routines used by validation classes.

    use Validation::Simple;

    my $rules = Validation::Simple->new;

    $rules->fields->add(
        email => {
            # email validation relies on a stashed object
            validation => sub {
                my ($self, $field, $params) = @_;
                return 0 if ! my $dbo = $self->stash('dbo');
                return 0 if ! $dbo->email_exists($field->value);
                return 1;
            }
        }
    );

    # elsewhere in the program
    $rules->stash(dbo => $database_object); # stash the database object

Error Handling

When validation fails, and it will, you need to be able to report what failed and why. Validation::Class give you complete control over error handling and messages. Errors can exist at the field-level and class-level (errors not specific to a particular field). All errors are wrapped in a Validation::Class::Errors container.

    use Validation::Simple;

    my $rules = Validation::Simple->new;

    # print a comma separated list of class and field errors
    print $rules->errors_to_string unless $rules->validate;

    # print a newline separated list of class and field errors
    print $rules->errors_to_string("\n") unless $rules->validate;

    # print a comma separated list of class and upper-cased field errors
    print $rules->errors_to_string(undef, sub{ ucfirst lc shift })

    # print total number of errors at the class and field levels
    print "Found %s errors", $rules->error_count;

    # return a hashref of fields with errors
    my $errors = $rules->error_fields;

    # get errors for specific fields only
    my @errors = $rules->get_errors('email', 'login');

Input Filtering

Filtering data is one fringe benefits of a good data validation framework. The process is also known as scrubbing or sanitizing data. The process ensures that the data being passed to the business logic will be clean and consistent.

Filtering data is not as simple and straight-forward as it may seem which is why it is necessary to think-through your applications interactions before implementation.

Filtering is the process of applying transformations to the incoming data. The problem with filtering is that it permanently alters the data input and in the event of a failure could report inconsistent error messages:

    use Validation::Simple;

    my $rules = Validation::Simple->new;

    $rules->fields->add(
        # even if the input is submitted as lowercase it will fail
        # the filter is run as a pre-process by default
        username => {
            filters => ['uppercase'],
            validation => sub {
                return 0 if $_[1]->value =~ /[A-Z]/;
                return 1;
            }
        }
    );

When designing a system to filter data, it is always necessary to differentiate pre-processing filters from post-processing filters. Validation::Class provides a filtering directive which designates certain fields to run filters in post-processing:

    $rules->fields->add(
        # if the input is submitted as lowercase it will pass
        username => {
            filters => ['uppercase'],
            filtering => 'post',
            validation => sub {
                return 0 if $_[1]->value =~ /[A-Z]/;
                return 1;
            }
        }
    );

Handling Failures

A data validation framework exists to handle failures, it is its main function and purpose, in-fact, the difference between a validation framework and a type-constraint system is how it responds to errors.

When a type-constraint system finds an error it raises an exception. Exception handling is the process of responding to the occurrence, during computation, of exceptions (anomalous or exceptional situations).

Typically the errors reported when an exception is raised includes a dump of the program's state up until the point of the exception which is apropos as exceptions are unexpected.

A data validation framework can also be thought-of as a type system but one that is specifically designed to expect input errors and report user-friendly error messages.

Validation::Class may encounter exceptions as programmers defined validation rules which remain mutable. Validation::Class provides attributes for determining how the validation engine reacts to exceptions and validation failures:

    use Validation::Simple;

    my $rules = Validation::Simple->new(
        ignore_failure => 1, # do not throw errors if validation fails
        ignore_unknown => 0, # throw errors if unknown directives are found
        report_failure => 0, # register errors if "method validations" fail
        report_unknown => 0, # register errors if "unknown directives" are found
    );

Data Validation

Once your fields are defined and you have your parameter rules configured as desired you will like use the validate method to perform all required operations. The validation operations occur in the following order:

    normalization   (resetting fields, clearing existing errors, etc)
    pre-processing  (applying filters, etc)
    validation      (processing directives, etc)
    post-processing (applying filters, etc)

What gets validated is determined by the state and arguments passed to the validate method. The validate method determines what to validate in the following order:

    checks the validation queue for fields
    checks arguments for regular expression objects and adds matching fields
    validates fields with matching parameters if no fields are specified
    validates all fields if no parameters are specified

It is also important to under what it means to declare a field as being required. A field is a data validation rule matching a specific parameter, A required field simply means that if-and-when a parameter is submitted, it is required to have a value. It does not mean that a field is always required to be validated.

Occasionally you may need to temporarily set a field as required or not-required for a specific validation operation. This requirement is referred to as the toggle function. The toggle function is enacted by prefixing a field name with a plus or minus sign (+|-) when passed to the validate method:

    use Validation::Simple;

    my $rules = Validation::Simple->new(fields => {...});

    # meaning, email is always required to have a value
    # however password and password2 can be submitted as empty strings
    # but if password and password2 have values they will be validated
    $rules->validate('+email', '-password', '-password2');

Here are a few examples and explanations of using the validate method:

    use Validation::Simple;

    my $rules = Validation::Simple->new(fields => {...});

    unless ($rules->validate) {
        # validate all fields with matching parameters
    }

    unless ($rules->validate) {
        # validate all fields because no parameters were submitted
    }

    unless ($rules->validate(qr/^email/)) {
        # validate all fields whose name being with email
        # e.g. email, email2, email_update
    }

    unless ($rules->validate('login', 'password')) {
        # validate the login and password specifically
        # regardless of what parameters have been set
    }

    unless ($rules->validate({ user => 'login', pass => 'password' })) {
        # map user and pass parameters to the appropriate fields as aliases
        # and validate login and password fields using the aliases
    }

EXTENSIBILITY

Validation::Class does NOT provide method modifiers but can be easily extended with Class::Method::Modifiers.

before

    before foo => sub { ... };

See "before method(s) => sub { ... }" in Class::Method::Modifiers for full documentation.

around

    around foo => sub { ... };

See "around method(s) => sub { ... }" in Class::Method::Modifiers for full documentation.

after

    after foo => sub { ... };

See "after method(s) => sub { ... }" in Class::Method::Modifiers for full documentation.

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.