# PODNAME: Validation::Class::Cookbook
# ABSTRACT: Recipes for Validation::Class

# VERSION

__END__

=pod

=head1 NAME

Validation::Class::Cookbook - Recipes for Validation::Class

=head1 VERSION

version 7.900038

=head1 BUILDING CLASSES

This recipe displays the usage of keywords to configure a validation class.

=head2 Problem

You want to know how to use the L<Validation::Class> keywords to define a
validation class.

=head2 Solution

Use the keywords exported by L<Validation::Class> to register validation rules,
templates, profiles, methods and filters.

=head2 Discussion

Your validation class can be thought of as your data-model/input-firewall. The
benefits this approach provides might require you to change your perspective
on parameter handling and workflow. Typically when designing an application we
tend to name parameters arbitrarily and validate the same data at various stages
during a program's execution in various places in the application stack. This
approach is inefficient and prone to bugs and security problems.

To get the most out of Validation::Class you should consider each parameter
hitting your application (individually) as a transmission fitting a very specific
criteria, yes, like a field in a data model.

Your validation rules will act as filters which will reject or accept and
format the transmission for use within your application, yes, almost exactly
like a firewall.

A validation class is defined as follows:

    package MyApp::Person;

    use Validation::Class;

    # a validation rule template

    mixin 'basic'  => {
        required   => 1,
        min_length => 1,
        max_length => 255,
        filters    => ['lowercase', 'alphanumeric']
    };

    # a validation rule

    field 'login'  => {
        mixin      => 'basic',
        label      => 'user login',
        error      => 'login invalid',
        validation => sub {

            my ($self, $field, $params) = @_;

            return $field->value eq 'admin' ? 1 : 0;

        }
    };

    # a validation rule

    field 'password'  => {
        mixin         => 'basic',
        label         => 'user password',
        error         => 'password invalid',
        validation    => sub {

            my ($self, $field, $params) = @_;

            return $field->value eq 'pass' ? 1 : 0;

        }
    };

    # a validation profile

    profile 'registration'  => sub {

        my ($self, @args) = @_;

        return $self->validate(qw(login password));

    };

    # an auto-validating method

    method 'registers'  => {

        input => 'registration',
        using => sub {

            my ($self, @args) = shift;

            # ... do something

        }

    };

    1;

The fields defined will be used to validate the specified input parameters.
You specify the input parameters at/after instantiation, parameters should take
the form of a hashref of key/value pairs passed to the params attribute, or
attribute/value pairs. The following is an example on using your validate class
to validate input in various scenarios:

    # web app
    package MyApp;

    use MyApp::User;
    use Misc::WebAppFramework;

    get '/auth' => sub {

        # get user input parameters
        my $params = shift;

        # initialize validation class and set input parameters
        my $user = MyApp::User->new(params => $params);

        unless ($user->registers) {

            # print errors to browser unless validation is successful
            return $user->errors_to_string;

        }

        return 'you have authenticated';

    };

A field can have aliases, parameter names that if detected will be mapped to
the parameter name matching the field definition. Multiple fields cannot have
the same alias defined, such a configuration would result in a runtime error.

    use MyApp::User;

    my $user = MyApp::User->new(params => $params);

    unless ($user->validate) {

        return $input->errors_to_string;

    }

    package MyApp::User;

    field 'email' => {
        ...,
        alias => [
            'emails',
            'email_address',
            'email_addresses'
        ]

    };

    package main;

    use MyApp::User;

    my  $user = MyApp::User->new(params => { email_address => '...' });

    unless ($user->validate('email'){

        return $user->errors_to_string;

    }

    # valid because email_address is an alias on the email field

=head1 INTEGRATING CLASSES AND FRAMEWORKS

This recipe displays methods of configuring your validation class to cooperate
with your pre-existing classes and object-system.

=head2 Problem

You want to know how to configure L<Validation::Class> to cooperate with
pre-existing classes or object systems like L<Mo>, L<Moo>, L<Mouse>, and L<Moose>.

=head2 Solution

Use a combination of techniques such as excluding keywords exported by
L<Validation::Class> and utilizing the initialize_validator method.

=head2 Discussion

L<Validation::Class> will atuomatically inject a method name
`initialize_validator` if a pre-existing `new` method is dicovered which allows
you to execute certain validation class normalization routines. When, the
initialize_validator method is called is not important, it is only important
that it is called before your object is used as a validation class object.

A validation class using Moose as an object system could be configured as follows:

    package MyApp::Person;

    use Moose;
    use Validation::Class qw(fld mxn);

    # the order in which these frameworks are used is important
    # loading Moose first ensures that the Moose::Object constructor
    # has precendence

    sub BUILD {

        my ($self, $params) = @_;

        $self->initialize_validator($params);

    }

    mxn 'basic'  => {
        required   => 1,
        min_length => 1,
        max_length => 255,
        filters    => ['lowercase', 'alphanumeric']
    };

    fld 'login'  => {
        mixin => 'basic',
        label => 'user login',
        error => 'login invalid'
    };

    fld 'password'  => {
        mixin => 'basic',
        label => 'user password',
        error => 'password invalid'
    };

    has 'profile' => (
        is  => 'rw',
        isa => 'MyApp::Person::Profile'
    );

    1;

=head1 FILTERING DATA

This recipe describes how to define filtering in your validation class rules.

=head2 Problem

You want to know how to define filters to sanatize and transform your data
although some transformations may need to occur after a successful validation.

=head2 Solution

Data validation rules can be configured to apply filtering as both pre-and-post
processing operations.

=head2 Discussion

Validation::Class supports pre/post filtering but is configured to pre-filter
incoming data by default. This means that based upon the filtering options
supplied within the individual fields, filtering will happen before validation
(technically at instantiation and again just before validation). As expected,
this is configurable via the filtering attribute.

A WORD OF CAUTION: Validation::Class is configured to pre-filter incoming data
which boosts application security and is best used with passive filtering
(e.g. converting character case - filtering which only alters the input in
predictable ways), versus aggressive filtering (e.g. formatting a telephone
number) which completely and permanently changes the incoming data ... so much
so that if the validation still fails ... errors that are reported may not
match the data that was submitted.

If you're sure you'd rather employ aggressive filtering, I suggest setting
the filtering attribute to 'post' for post-filtering or setting it to null
and applying the filters manually by calling the apply_filters() method.

=head1 DELEGATING VALIDATION

This recipe describes how to separate validation logic between multiple related
classes.

=head2 Problem

You want to know how to define multiple validation classes and pass input
data and input parameters between them.

=head2 Solution

Use classes as validation domains, as a space to logically group related
validation rules, then use built-in methods to have multiple validation classes
validate in-concert.

=head2 Discussion

For larger applications where a single validation class might become cluttered
and inefficient, Validation::Class comes equipped to help you separate your
validation rules into separate classes.

The idea is that you'll end up with a main validation class (most likely empty)
that will simply serve as your point of entry into your relative (child)
classes. The following is an example of this:

    package MyApp::User;

    use Validation::Class;

    field name      => { ... };
    field email     => { ... };
    field login     => { ... };
    field password  => { ... };

    package MyApp::Profile;

    use Validation::Class;

    field age       => { ... };
    field sex       => { ... };
    field birthday  => { ... };

    package MyApp;

    use Validation::Class;

    set classes => 1;

    package main;

    my $input = MyApp->new(params => $params);

    my $user = $input->class('user');

    my $profile = $input->class('profile');

    1;

=head1 INTROSPECT AND EXTEND

This recipe describes how to peek under the curtain and leverage the framework
for other purposes.

=head2 Problem

You want to know how to use your data validation classes to perform other tasks
programatically (e.g. generate documentation, etc).

=head2 Solution

By using the prototype class associated with your validation class you can
introspect it's configuration and perform additional tasks programatically.

=head2 Discussion

Most users will never venture beyond the public API, but powerful abilities
await the more adventureous developer and this section was written specifically
for you. To assist you on along your journey, let me explain exactly what
happens when you define and instantiate a validation class.

Classes are defined using keywords (field, mixin, filter, etc) which register
rule definitions on a cached class profile (of-sorts) associated with the class
which is being constructed. On instantiation, the cached class profile is cloned
then merged with any arguments provided to the constructor, this means that even
in a persistent environment the original class profile is never altered.

To begin introspection, simply look into the attributes attached to the class
prototype, e.g. fields, mixins, filters, etc., the following examples will give
you an idea of how to use introspection to extend your application code using
Validation::Class.

Please keep in mind that Validation::Class is likely to already have most of the
functionalty you would need to introspect your codebase. The following is an
introspection design template that will work in most cases:

    package MyApp::Introspect;

    use Validation::Class;

    load classes => 'MyApp'; # load MyApp and all child classes

    sub per_class {

        my ($self, $code) = @_;

        my %relatives = %{$self->proto->settings->{relatives}};

        while (my($parent, $children) =  each(%relatives)) {

            while (my($nickname, $namespace) = each(%{$children})) {

                # do something with each class
                $code->($namespace);

            }

        }

    }

    sub per_field_per_class {

        my ($self, $code) = @_;

        $self->per_class(sub{

            my $namespace = shift;

            my $class = $namespace->new;

            foreach my $field ($class->fields->values) {

                # do something with each field in each class
                $code->($class, $class->fields->{$field});

            }

        });

    }

=head1 CLIENT-SIDE VALIDATION

This recipe describes how to generate JSON objects which can be used to validate
user input in the web-browser (client-side).

=head2 Problem

You want to know how to make the most out of your data validation rules by
making your configuration available as JSON objects in the browser.

=head2 Solution

Using introspection, you can leverage the prototype class associated with your
validation class to generate JSON objects based on your validation class
configuration.

=head2 Discussion

In the context of a web-application, it is often best to perform the initial
input validation on the client (web-browser) before submitting data to the
server for further validation and processing. In the following code we will
generate javascript objects that match our Validation::Class data models which
we will then use with some js library to validate form data, etc.

... example validation class

    package MyApp::Model;

    use Validation::Class;
    use Validation::Class::Plugin::JavascriptObjects;

    mxn scrub => {
        filters => ['trim', 'strip']
    };

    fld login => {
        mixin    => 'scrub'
        email    => 1,
        required => 1,
        alias    => 'user',
    };

    fld password    => {
        mixin       => 'scrub',
        required    => 1,
        alias       => 'pass',
        min_length  => 5,
        min_symbols => 1,
        min_alpha   => 1,
        min_digits  => 1
    };

... in your webapp controller

    get '/js/model'   => sub {

        my $model     = MyApp::Model->new;

        # generate the JS object
        my $data = $model->plugin('javascript_objects')->render(
            namespace => 'validate.model',
            fields    => [qw/email password/],
            include   => [qw/required email minlength maxlength/]
        )

        return print $data;

    };

The output of the /js/model route should generate a javascript object which
looks similar to the following:

    var validate = {
        "model" : {
            "email" : {
               "minlength" : 3,
               "required" : 1,
               "maxlength" : 255
            },
            "password" : {
               "minlength" : 5,
               "required" : 1,
               "maxlength" : 255
            }
        }
    };

If its not obvious yet, we can now easily use this generated javascript API with
jQuery (or other client-side library) to validate form data, etc.

    <!DOCTYPE html>
    <html>
        <head>
            <title>AUTH REQUIRED</title>
            <script type="text/javascript" src="/js/jquery.js"></script>
            <script type="text/javascript" src="/js/jquery.validate.js"></script>
            <script type="text/javascript" src="/js/model"></script>
            <script type="text/javascript">
                $(document).ready(function() {
                    $("#form").validate({rules:validate.model});
                });
            </script>
        </head>
        <body>
            <div>[% input.errors_to_string %]</div>
            <form id="form" autocomplete="off" method="post" action="/">
            <fieldset>
                <legend><h2><strong>Halt</strong>, who goes there?</h2></legend>
                <label for="email">Email</label><br/>
                <input id="email" name="email" value="" /><br/>
                <label for="password">Password</label><br/>
                <input id="password" name="password" type="password" /><br/>
                <br/><input type="submit" value="Submit" />
            </fieldset>
            </form>
        </body>
    </html>

=head1 AUTHOR

Al Newkirk <anewkirk@ana.io>

=head1 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.

=cut
