Al Newkirk > Validation-Class-7.900015 > Validation::Class::Cookbook

Download:
Validation-Class-7.900015.tar.gz

Annotate this POD

Website

View/Report Bugs
Source   Latest Release: Validation-Class-7.900056

NAME ^

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

VERSION ^

version 7.900015

BUILDING CLASSES ^

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

Problem

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

Solution

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

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 login',
        error         => 'login 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

FILTERING DATA ^

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

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.

Solution

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

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.

DELEGATING VALIDATION ^

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

Problem

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

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.

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 MyVal::User;

    use Validation::Class;

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

    package MyVal::Profile;

    use Validation::Class;

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

    package MyVal;

    use Validation::Class;

    set classes => 1;

    package main;

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

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

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

    1;

INTROSPECT AND EXTEND ^

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

Problem

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

Solution

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

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;

    set classes => 'MyApp'; # load MyApp and all MyApp::* child classes

    sub per_class {

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

        $self->proto->relatives->each(sub {

            $code->($_[1]);

        });

    }

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

            }

        });

    }

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).

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.

Solution

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

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

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.

syntax highlighting: