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

NAME

Validator::Custom::Guides - Validator::Custom Guides

GUIDES

1. Basic usages

Create a new Validator::Custom object.

    use Validator::Custom;
    my $vc = Validator::Custom->new;

Data used in validation must be hash reference.

    my $data = { 
        age => 19, 
        name => 'Ken Suzuki'
    };

Register constraint function. constraint must be sub reference, which check if the value is valid.

    $vc->register_constraint(
        int => sub {
            my $value    = shift;
            my $is_valid = $value =~ /^\d+$/;
            return $is_valid;
        },
        not_blank => sub {
            my $value = shift;
            my $is_valid = $value ne '';
            return $is_valid;
        },
        length => sub {
            my ($value, $args) = @_;
            my ($min, $max) = @$args;
            my $length = length $value;
            my $is_valid = $length >= $min && $length <= $max;
            return $is_valid;
        },
    );

Rule for validation has a specific format. the pairs of parameter name and constraint expressions. the format detail is explained in "3. Syntex of rule".

    my $rule = [
        age => [
            'int'
        ],
        name => [
            ['not_blank',        "Name must be exists"],
            [{length => [1, 5]}, "Name length must be 1 to 5"]
        ],
        # PARAMETER_NAME => [
        #    CONSTRIANT_EXPRESSION1
        #    CONSTRAINT_EXPRESSION2
        # ]
    ];

Validate the data. validate() return Validator::Custom::Result object.

    my $result = $vc->validate($data, $rule);

2. Result of validation

Validator::Custom::Result object has the result of validation. See Validator::Custom::Result in detail.

Examples:

Check if the data has missing parameter and invalid parameter. and print message unless the parameter is valid.

    if ($result->has_missing) {
        # ...
    }
    elsif ($result->has_invalid) {
        
        print $result->message('title')
          unless $result->is_valid('title');
        
        print $result->message('author')
          unless $result->is_valid('author');
    }

Get all message

    if ($result->has_missing) {
        # ...
    }
    elsif ($result->has_invalid) {
        
        my $messages = $result->messages;
    }

Combination with HTML::FillInForm

    unless ($result->is_ok) {
        
        my $html = get_something_way();
        
        # Fill in form
        $html = HTML::FillInForm->fill(
            \$html, $result->raw_data,
            ignore_fields => $result->invalid_params
        );
        
        # Do something
    }

3. Syntax of rule

Basic syntax

Rule must be array reference. This is for keeping the order of invalid parameter names.

    my $rule = [
    
    ];

Rule contains the pairs of parameter name and list of constraint expression.

    my $rule = [
        name => [
            'not_blank'
        ],
        age => [
            'not_blank',
            'int'
        ]
        price => {default => 1000, message => 'price must be integer'} => [
            'int'
        ]

        # PARAMETER_NAME => OPTIONS(this is optional) => [
        #    CONSTRIANT_EXPRESSION1
        #    CONSTRAINT_EXPRESSION2
        # ]
    ];

Constraint expression

Constraint expression is one of four.

  1. constraint name

        CONSTRAINT_NAME
  2. constraint name and message

        [CONSTRIANT_NAME, MESSAGE]
  3. constraint name and argument

        {CONSTRAINT_NAME => ARGUMENT}
  4. constraint name and argument and message

        [{CONSTRAINT_NAME => ARGUMENT}, MESSAGE]

Example:

    my $rule = [
        age => [
            # 1. constraint name
            'defined',
            
            # 2. constraint name and message
            ['not_blank', 'Must be not blank'],
            
            # 3. constraint name and argument
            {length => [1, 5]},
            
            # 4. constraint name and argument and message
            [{regex => qr/\d+/}, 'Invalid string']
        ]
    ];

Options

Options can be set.

1. message

Message when the result has invalid parameter

     {message => "This key is invalid"}
2. default

default value. This value is set if the result has missing parameter or has invalid parameter.

    {default => 5}
3. copy

the value is copied to result's data or not. default to 1.

    {copy => 0}

Multi-parameters validation

Multi-parameters validation is available.

    $data = {password1 => 'xxx', password2 => 'xxx'};

    $rule = [
        {password_check => [qw/password1 password2/]} => [
            ['duplication', 'Two password must be equal']
        ]
    ];

"password1" and "password2" is parameter names. "password_check" is result key.

You can also use the reference of regular expression.

    $data = {person1 => 'Taro', person2 => 'Rika', person3 => 'Ken'};

    $rule = [
        {password_check => qr/^person;/} => [
            'merge',
            'trim',
            'not_blank'
        ]
    ];

Multi-values validation

Multi-values validation is available if the parameter value is array reference. Add "@" mark before constraint name.

    $data = {
        nums => [1, 2, 3]
    };
    
    $rule = [
        'nums' => [
            '@int'
        ]
    ];

Validation of OR condition

OR condition validation is available. use || for or condition.

    $rule = [
        email => [
            'blank || email'
        ]
    ];

Negative validation

You can negativate a constraint function by adding '!' to the constraint name.

    $rule = [
        age => [
            '!int';
        ],
    ];

This means that "age" is not int.

You can also combine this and Multi-parameters validation

    $rule = [
        ages => [
            '@!int';
        ]
    ];

4. Specification of constraint

I explain the specification of constraint.

    # Register constraint
    $vc->register_constraint(
        consrtaint_name => sub {
            my ($value, $args, $vc) = @_;
            
            # Do something
            
            return $is_valid;
        }
    )

Arguments and return value

Constraint function receive three arguments.

  1. value

  2. argument

  3. Validator::Custom object

1. value

This is the value of data.

    my $data = {name => 'Ken Suzuki'};

In this example, value is 'Ken Suzuki'

2. argument

You can pass argument to consraint in the rule.

    my $rule = [
        name => [
            {length => [1, 5]}
        ]
    ];

In this example, argument is [1, 5].

And this function must return a value to check if the value is valid.

In Multi-parameters validation, values is packed to array reference, value is ['xxx', 'xxx'].

    $data = {password1 => 'xxx', password2 => 'xxx'};

    $rule = [
        {password_check => [qw/password1 password2/]} => [
            ['duplication', 'Two password must be equal']
        ]
    ];

Filtering function

Constraint function can be also return converted value. If you return converted value, you must return array reference, which contains two element, value to check if the value is valid, and converted value.

    $vc->register_constraint(
        trim => sub {
            my $value = shift;
            
            $value =~ s/^\s+//;
            $value =~ s/\s+$//;
            
            return [1, $value];
        }
    );

5. Extending

Validator::Custom is easy to extend. To register constarint, use register_constraint in constructor.

    package YourValidator;
    use base 'Validator::Custom';
    
    sub new {
        my $self = shift->SUPER::new(@_);
        $self->register_constraint(
            defined  => sub { defined $_[0] }
        );
        return $self;
    }
    
    1;
    

Validator::Custom::HTMLForm is good examples.

6. Advanced features

Data filtering

If data is not hash reference, you can converted data to hash reference by data_filter().

    $vc->data_filter(
        sub { 
            my $data = shift;
            
            # Convert data to hash reference
            
            return $data;
        }
    );

Stock of messages

By default, all parameters is checked by validate(). If you want to check only if the data is valid, it is good to finish validation when the invalid value is found. If you set error_stock to 0, Validation is finished soon after invalid value is found.

    $vc->error_stock(0);
    

DEPRECATED METHODS

These attributes and methods are deprecated.

error_infos, add_error_info, errors, error, errors_to_hash, invalid_keys, remove_error_info

If you see the description of these methods, see document older than 0.1403.