Validator::Custom::Guides - Validator::Custom Guides
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);
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 }
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.
constraint name
CONSTRAINT_NAME
constraint name and message
[CONSTRIANT_NAME, MESSAGE]
constraint name and argument
{CONSTRAINT_NAME => ARGUMENT}
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.
Message when the result has invalid parameter
{message => "This key is invalid"}
default value. This value is set if the result has missing parameter or has invalid parameter.
{default => 5}
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.
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. Write parameter name repeatedly.
$rule = [ email => [ 'blank' ], email => [ 'not_blank', 'emai_address' ] ];
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'; ] ];
Shared rule
Can share rule with all parameters. Shared rule is added to the head of each list of constraint expression.
$vc->shared_rule([ ['defined', 'Must be defined'], ['trim'], ['not_blank', 'Must be not blank'] ]);
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.
value
argument
Validator::Custom object
This is the value of data.
my $data = {name => 'Ken Suzuki'};
In this example, value is 'Ken Suzuki'
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'].
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]; } );
Validator::Custom is easy to extend. To register constarint, use register_constraint in constructor.
register_constraint
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.
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);
These attributes and methods are deprecated.
error_infos, add_error_info, errors, error, errors_to_hash, invalid_keys, remove_error_info
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.
To install Validator::Custom, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Validator::Custom
CPAN shell
perl -MCPAN -e shell install Validator::Custom
For more information on module installation, please visit the detailed CPAN module installation guide.