# NAME

Validation::Class - Powerful Data Validation Framework

# VERSION

version 7.900018

# SYNOPSIS

    use Validation::Class::Simple::Streamer;

    my $input = Validation::Class::Simple::Streamer->new($parameters);

    # data validation rules for the username parameter
    $input->check('username')->required->between('5-255');
    $input->filters([qw/trim strip/]);

    # data validation rule for the password parameter
    $input->check('password')->required->between('5-255')->min_symbols(1);
    $input->filters([qw/trim strip/]);

    # perform validation
    unless ($input) {
        # handle the failures
    }

# DESCRIPTION

Validation::Class is a scalable data validation library with interfaces for
applications of all sizes. [Validation::Class::Simple::Streamer](http://search.cpan.org/perldoc?Validation::Class::Simple::Streamer) is a great way
to leverage this library for ad-hoc use-cases, [Validation::Class::Simple](http://search.cpan.org/perldoc?Validation::Class::Simple)
is very well suited for applications of moderate sophistication where it makes
sense to pre-declared validation rules, and Validation::Class is designed to
transform class namespaces into data validation domains where consistency and
reuse are primary concerns.

Validation::Class provides an extensible framework for defining reusable data
validation rules. It ships with a complete set of pre-defined validations and
filters referred to as ["directives"](http://search.cpan.org/perldoc?Validation::Class::Directives#DIRECTIVES).
The core feature-set consist of self-validating methods, validation profiles,
reusable validation rules and templates, pre and post input filtering, class
inheritance, automatic array handling, and extensibility (e.g. overriding
default error messages, creating custom validators, creating custom input
filters and much more). Validation::Class promotes DRY (don't repeat yourself)
code. The main benefit in using Validation::Class is that the architecture is
designed to increase the consistency of data input handling. The following is
a more traditional usage of Validation::Class:

    package MyApp::Person;

    use Validation::Class;

    # data validation template
    mixin basic     => {
        required    => 1,
        max_length  => 255,
        filters     => [qw/trim strip/]
    };

    # data validation rules for the username parameter
    field username  => {
        mixin       => 'basic',
        min_length  => 5
    };

    # data validation rules for the password parameter
    field password  => {
        mixin       => 'basic',
        min_length  => 5,
        min_symbols => 1
    };

    # elsewhere in your application
    my $person = MyApp::Person->new(username => 'admin', password => 'secr3t');

    # validate rules on the person object
    unless ($person->validates) {
        # handle the failures
    }

    1;

# QUICKSTART

If you are looking for a simple in-line data validation module built using the
same tenets and principles as Validation::Class, please review
[Validation::Class::Simple](http://search.cpan.org/perldoc?Validation::Class::Simple).

# 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](http://search.cpan.org/perldoc?Validation::Class::Whitepaper).

# KEYWORDS

## attribute

The attribute keyword (or has) registers a class attribute. This is only a
minimalistic variant of what you may have encountered in other object systems.

    package MyApp::Person;

    use Validate::Class;

    attribute 'first_name' => 'Peter';
    attribute 'last_name'  => 'Venkman';
    attribute 'full_name'  => sub {

        my ($self) = @_;

        return join ', ', $self->last_name, $self->first_name;

    };

    1;

The attribute keyword takes two arguments, the attribute name and a constant or
coderef that will be used as its default value.

## build

The build keyword (or bld) registers a coderef to be run at instantiation much
in the same way the common BUILD routine is used in modern OO frameworks.

    package MyApp::Person;

    use Validation::Class;

    build sub {

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

        # run after instantiation in the order declared

    };

The build keyword takes one argument, a coderef which is passed the instantiated
class object.

## directive

The directive keyword (or dir) registers custom validator directives to be used
in your field definitions. This is a means of extending the list of directives
per instance. See the list of core directives, [Validation::Class::Directives](http://search.cpan.org/perldoc?Validation::Class::Directives),
or review [Validation::Class::Directive](http://search.cpan.org/perldoc?Validation::Class::Directive) for insight into creating your own
CPAN installable directives.

    package MyApp::Directives;

    use Validation::Class 'directive';

    use Data::Validate::Email;

    directive 'isa_email_address' => sub {

        my ($self, $proto, $field, $param) = @_;

        my $validator = Data::Validate::Email->new;

        unless ($validator->is_email($param)) {

            my $handle = $field->label || $field->name;

            $field->errors->add("$handle must be a valid email address");

            return 0;

        }

        return 1;

    };

    package MyApp::Person;

    use Validate::Class;

    use MyApp::Directives;

    field 'email_address' => {
        isa_email_address => 1
    };

    1;

The directive keyword takes two arguments, the name of the directive and a
coderef which will be used to validate the associated field. The coderef is
passed four ordered parameters; a directive object, the class prototype object,
the current field object, and the matching parameter's value. The validator
(coderef) is evaluated by its return value as well as whether it altered any
error containers.

## field

The field keyword (or fld) registers a data validation rule for reuse and
validation in code. The field name should correspond with the parameter name
expected to be passed to your validation class or validated against.

    package MyApp::Person;

    use Validation::Class;

    field 'username' => {
        required   => 1,
        min_length => 1,
        max_length => 255
    };

The field keyword takes two arguments, the field name and a hashref of key/values
pairs known as directives. For more information on pre-defined directives, please
review the ["list of core directives"](http://search.cpan.org/perldoc?Validation::Class::Directives#DIRECTIVES).

The field keyword also creates accessors which provide easy access to the
field's corresponding parameter value(s). Accessors will be created using the
field's name as a label having any special characters replaced with an
underscore.

    field 'send-reminders' => { # accessor will be created as send_reminders
        length   => 1
    };

Protip: Field directives are used to validate scalar and array data. Don't use
fields to store and validate objects. Please see the \*has\* keyword instead or
use an object system with type constraints like [Moose](http://search.cpan.org/perldoc?Moose).

## filter

The filter keyword (or flt) registers custom filters to be used in your field
definitions. It is a means of extending the pre-existing filters declared by
the ["filters directive"](http://search.cpan.org/perldoc?Validation::Class::Directive::Filters) before
instantiation.

    package MyApp::Directives;

    use Validation::Class;

    filter 'flatten' => sub {

        $_[0] =~ s/[\t\r\n]+/ /g;
        return $_[0];

    };

    package MyApp::Person;

    use Validate::Class;

    use MyApp::Directives;

    field 'biography' => {
        filters => ['trim', 'flatten']
    };

    1;

The filter keyword takes two arguments, the name of the filter and a
coderef which will be used to filter the value the associated field. The coderef
is passed the value of the field and that value MUST be operated on directly.
The coderef should also return the transformed value.

## load

The load keyword (or set), which can also be used as a class method, provides
options for extending the current class by declaring roles, plugins, etc.

The process of applying roles to the current class mainly involves copying the
subject's methods and prototype configuration.

    package MyApp::Person;

    use Validation::Class;

    load role => 'MyApp::User';

    1;

The \`roles\` (or role) option is used to load and inherit functionality from
other validation classes. These classes should be used and thought-of as roles
although they can also be fully-functioning validation classes. This option
accepts an arrayref or single argument.

    package MyApp::Person;

    use Validation::Class;

    load roles => ['MyApp::User', 'MyApp::Visitor'];

    1;

## message

The message keyword (or msg) registers a class-level error message template that
will be used in place of the error message defined in the corresponding directive
class if defined. Error messages can also be overridden at the individual
field-level as well. See the [Validation::Class::Directive::Messages](http://search.cpan.org/perldoc?Validation::Class::Directive::Messages) for
instructions on how to override error messages at the field-level.

    package MyApp::Person;

    use Validation::Class;

    field email_address => {
        required   => 1,
        min_length => 3,
        messages   => {
            # field-level error message override
            min_length => '%s is not even close to being a valid email address'
        }
    };

    # class-level error message overrides
    message required   => '%s is needed to proceed';
    message min_length => '%s needs more characters';

    1;

The message keyword takes two arguments, the name of the directive whose error
message you wish to override and a string which will be used to as a template
which is feed to sprintf to format the message.

## method

The method keyword (or mth) is used to register an auto-validating method.
Similar to method signatures, an auto-validating method can leverage pre-existing
validation rules and profiles to ensure a method has the required data necessary
for execution.

    package MyApp::Person;

    use Validation::Class;

    method 'register' => {

        input  => ['name', '+email', 'username', '+password', '+password2'],
        output => ['+id'], # optional output validation, dies on failure
        using  => sub {

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

            # do something registrationy

            $self->id(...); # set the ID field for output validation

            return $self;

        }

    };

    package main;

    my $person = MyApp::Person->new(params => $params);

    if ($person->register) {

        # handle the successful registration

    }

    1;

The method keyword takes two arguments, the name of the method to be created
and a hashref of required key/value pairs. The hashref must have an \`input\`
key whose value is either an arrayref of fields to be validated, or a scalar
value which matches (a validation profile or auto-validating method name). The
hashref must also have a \`using\` key whose value is a coderef which will be
executed upon successfully validating the input. The \`using\` key/coderef can be
omitted when a sub-routine of the same name prefixed with an underscore is
present. Whether and what the method returns is yours to decide. The method will
return 0 if validation fails.

Optionally the required hashref can have an \`output\` key whose value is either
an arrayref of fields to be validated, or a scalar value which matches
(a validation profile or auto-validating method name) which will be used to
perform data validation __after__ the aforementioned coderef has been executed.

Please note that output validation failure will cause the program to die,
the premise behind this decision is based on the assumption that given
successfully validated input a routine's output should be predictable and if an
error occurs it is most-likely a program error as opposed to a user error.

See the ignore\_failure and report\_failure attributes on the prototype to control
how method input validation failures are handled.

## mixin

The mixin keyword (or mxn) registers a validation rule template that can be
applied (or "mixed-in") to any field by specifying the mixin directive. Mixin
directives are processed first so existing field directives will override any
directives created by the mixin directive.

    package MyApp::Person;

    use Validation::Class;

    mixin 'boilerplate' => {
        required   => 1,
        min_length => 1,
        max_length => 255
    };

    field 'username' => {
        # min_length, max_length, .. required will be overridden
        mixin    => 'boilerplate',
        required => 0
    };

Since version 7.900015, all classes are automatically configured with the following
default mixins for the sake of convenience:

    mixin ':flg' => {
        required   => 1,
        min_length => 1,
        filters    => [qw/trim strip numeric/],
        between    => [0, 1]
    };

    mixin ':num' => {
        required   => 1,
        min_length => 1,
        filters    => [qw/trim strip numeric/]
    };

    mixin ':str' => {
        required   => 1,
        min_length => 1,
        filters    => [qw/trim strip/]
    };

The mixin keyword takes two arguments, the mixin name and a hashref of key/values
pairs known as directives.

## profile

The profile keyword (or pro) registers a validation profile (coderef) which as
in the traditional use of the term is a sequence of validation routines that
validates data relevant to a specific action.

    package MyApp::Person;

    use Validation::Class;

    profile 'check_email' => sub {

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

        if ($self->email_exists) {
            my $email = $self->fields->get('email');
            $email->errors->add('Email already exists');
            return 0;
        }

        return 1;

    };

    package main;

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

    unless ($user->validate_profile('check_email')) {
        # handle failures
    }

The profile keyword takes two arguments, a profile name and coderef which will
be used to execute a sequence of actions for validation purposes.

# METHODS

## new

The new method instantiates a new class object, it performs a series of actions
(magic) required for the class function properly, and for that reason, this
method should never be overridden. Use the build keyword for hooking into the
instantiation process.

In the event a foreign \`new\` method is detected, an \`initialize\_validator\`
method will be injected into the class containing the code (magic) necessary to
normalize your environment.

    package MyApp::Person;

    use Validation::Class;

    # hook
    build sub {

        my ($self, @args) = @_; # on instantiation

    };

    sub new {

        # rolled my own
        my $self = bless {}, shift;

        # execute magic
        $self->initialize_validator;

    }

## prototype

The prototype method (or proto) returns an instance of the associated class
prototype. The class prototype is responsible for manipulating and validating
the data model (the class). It is not likely that you'll need to access
this method directly, see [Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype).

    package MyApp::Person;

    use Validation::Class;

    package main;

    my $person = MyApp::Person->new;

    my $prototype = $person->prototype;

# PROXY METHODS

Validation::Class mostly provides sugar functions for modeling your data
validation requirements. Each class you create is associated with a \*prototype\*
class which provides the data validation engine and keeps your class namespace
free from pollution, please see [Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype) for more
information on specific methods and attributes.

Validation::Class injects a few proxy methods into your class which are
basically aliases to the corresponding prototype 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](http://search.cpan.org/perldoc?Validation::Class::Prototype#class) for full documentation.

## clear\_queue

    $self->clear_queue;

See ["clear\_queue" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#clear\_queue) for full documentation.

## error\_count

    $self->error_count;

See ["error\_count" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#error\_count) for full documentation.

## error\_fields

    $self->error_fields;

See ["error\_fields" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#error\_fields) for full documentation.

## errors

    $self->errors;

See ["errors" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#errors) for full documentation.

head2 errors\_to\_string

    $self->errors_to_string;

See ["errors\_to\_string" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#errors\_to\_string) for full
documentation.

## get\_errors

    $self->get_errors;

See ["get\_errors" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#get\_errors) for full documentation.

## get\_fields

    $self->get_fields;

See ["get\_fields" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#get\_fields) for full documentation.

## get\_hash

    $self->get_hash;

See ["get\_hash" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#get\_hash) for full documentation.

## get\_params

    $self->get_params;

See ["get\_params" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#get\_params) for full documentation.

## get\_values

    $self->get_values;

See ["get\_values" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#get\_values) for full documentation.

## fields

    $self->fields;

See ["fields" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#fields) for full documentation.

## filtering

    $self->filtering;

See ["filtering" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#filtering) for full documentation.

## ignore\_failure

    $self->ignore_failure;

See ["ignore\_failure" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#ignore\_failure) for full
documentation.

## ignore\_unknown

    $self->ignore_unknown;

See ["ignore\_unknown" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#ignore\_unknown) for full
documentation.

## param

    $self->param;

See ["param" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#param) for full documentation.

## params

    $self->params;

See ["params" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#params) for full documentation.

## queue

    $self->queue;

See ["queue" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#queue) for full documentation.

## report\_failure

    $self->report_failure;

See ["report\_failure" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#report\_failure) for full
documentation.

## report\_unknown

    $self->report_unknown;

See ["report\_unknown" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#report\_unknown) for full documentation.

## reset\_errors

    $self->reset_errors;

See ["reset\_errors" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#reset\_errors) for full documentation.

## reset\_fields

    $self->reset_fields;

See ["reset\_fields" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#reset\_fields) for full documentation.

## reset\_params

    $self->reset_params;

See ["reset\_params" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#reset\_params) for full documentation.

## set\_errors

    $self->set_errors;

See ["set\_errors" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#set\_errors) for full documentation.

## set\_fields

    $self->set_fields;

See ["set\_fields" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#set\_fields) for full documentation.

## set\_params

    $self->set_params;

See ["set\_params" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#set\_params) for full documentation.

## set\_method

    $self->set_method;

See ["set\_method" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#set\_method) for full documentation.

## stash

    $self->stash;

See ["stash" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#stash) for full documentation.

## validate

    $self->validate;

See ["validate" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#validate) for full documentation.

## validate\_method

    $self->validate_method;

See ["validate\_method" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#validate\_method) for full documentation.

## validate\_profile

    $self->validate_profile;

See ["validate\_profile" in Validation::Class::Prototype](http://search.cpan.org/perldoc?Validation::Class::Prototype#validate\_profile) for full documentation.

# EXTENSIBILITY

Validation::Class does NOT provide method modifiers but can be easily extended
with [Class::Method::Modifiers](http://search.cpan.org/perldoc?Class::Method::Modifiers).

## before

    before foo => sub { ... };

See ["before method(s) => sub { ... }" in Class::Method::Modifiers](http://search.cpan.org/perldoc?Class::Method::Modifiers#before method(s) => sub { ... }) for full
documentation.

## around

    around foo => sub { ... };

See ["around method(s) => sub { ... }" in Class::Method::Modifiers](http://search.cpan.org/perldoc?Class::Method::Modifiers#around method(s) => sub { ... }) for full
documentation.

## after

    after foo => sub { ... };

See ["after method(s) => sub { ... }" in Class::Method::Modifiers](http://search.cpan.org/perldoc?Class::Method::Modifiers#after method(s) => sub { ... }) for full
documentation.

# SEE ALSO

__If you have simple data validation needs, please review:__

- [Validation::Class::Simple](http://search.cpan.org/perldoc?Validation::Class::Simple)

Validation::Class validates strings, not structures. If you need a means for
validating object types you should be using a modern object system like [Mo](http://search.cpan.org/perldoc?Mo),
[Moo](http://search.cpan.org/perldoc?Moo), [Mouse](http://search.cpan.org/perldoc?Mouse), or [Moose](http://search.cpan.org/perldoc?Moose). Alternatively you could use [Params::Validate](http://search.cpan.org/perldoc?Params::Validate).

In the event that you would like to look elsewhere for your data validation
needs, the following is a list of other validation libraries/frameworks you
might be interested in. If I've missed a really cool new validation library
please let me know.

- [HTML::FormHandler](http://search.cpan.org/perldoc?HTML::FormHandler)

    This library seems to be the defacto standard for designing Moose classes with
    HTML-centric data validation rules.

- [Data::Verifier](http://search.cpan.org/perldoc?Data::Verifier)

    This library is a great approach towards adding robust validation logic to
    your existing Moose-based codebase.

- [Validate::Tiny](http://search.cpan.org/perldoc?Validate::Tiny)

    This library is nice for simple use-cases, it has virtually no dependencies
    and solid test coverage.

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