=encoding utf-8 =head1 NAME Mojolicious::Plugin::Vparam - Mojolicious plugin validator for GET/POST data. =head1 DESCRIPTION Features: =over =item * Simple syntax or full featured =item * Many predefined types =item * Shortcuts for the most common uses =item * Filters complementary types =item * Support arrays and hashes of values =item * Support HTML checkbox as bool =item * Simple JSON values extraction and validation using JSON Pointer from L. =item * Simple XML/HTML values extraction and validation using CSS selector engine from L or XPath from L. =item * Validate all parameters at once and get hash to simple use in any Model =item * Manage validation errors =item * Full Mojolicious::Validator::Validation integration =back This module use simple parameters types B, B, B, B, etc. to validate. Instead of many other modules you mostly not need add specific validation subs or rules. Just set parameter type. But if you want sub or regexp you can do it too. =head1 SYNOPSIS # Add plugin in startup $self->plugin('Vparam'); # Use in controller $login = $self->vparam(login => 'str'); $passw = $self->vparam(password => 'password', size => [8, 100]); $email = $self->vparam(email => 'email', optional => 1); $session = $self->vparam(session => 'bool', default => 1); $ids = $self->vparam(ids => '@int'); =head1 METHODS =head2 vparam Get one parameter. By default parameter is required. # Simple get one parameter $param1 = $self->vparam(date => 'datetime'); # Or more syntax $param2 = $self->vparam(count => {type => 'int', default => 1}); # Or more simple syntax $param2 = $self->vparam(count => 'int', default => 1); =head2 vparams Get many parameters as hash. By default all parameters are required. %params = $self->vparams( # Simple syntax name => 'str', password => qr{^\w{8,32}$}, myparam => sub { $_[1] && $_[1] eq 'ok' ? 1 : 0 } }, someone => ['one', 'two', 'tree'], # More syntax from => { type => 'date', default => '' }, to => { type => 'date', default => '' }, id => { type => 'int' }, money => { regexp => qr{^\d+(?:\.\d{2})?$} }, myparam => { post => sub { $_[1] && $_[1] eq 'ok' ? 1 : 0 } }, # Checkbox isa => { type => 'bool', default => 0 }, ); =head2 vsort Like I but add some keys to simple use with tables. Example: # HTML - table with controls and filters Order by: Order direction: Count per page: Filter by name: Any other filters ... # Controller %params = $self->vsort( -sort => ['name', 'date', ...], # next as vparams name => 'text', ... ); =over =item page Page number. Default: 1. You can set different name by I config parameter. If you set undef then parameter is not apply. =item rws Rows on page. Default: 25. You can set different name by I config parameter. You can set different default by I config parameter. If you set undef then parameter is not apply. =item oby Column number for sorting. Default: 1 - in many cases first database column is primary key. You can set different name by I config parameter. If you set undef then parameter is not apply. Value of B The value will be automatically mapped to the column name using the L attribute. Also, the value will be checked for proper mapping. So you do not need to worry about it. =item ods Sort order ASC|DESC. Default: ASC. You can set different name by I config parameter. If you set undef then parameter is not apply. =back =head2 verror $name Get parameter error string. Return 0 if no error. # Get error print $self->verror('myparam') || 'Ok'; # Set error $self->verror('myparam', {message => 'Error message'}) =head2 verrors Return erorrs count in scalar context. In list context return erorrs hash. # List context get hash my %errors = $self->verrors; # Scalar context get count die 'Errors!' if $self->verrors; =head2 vclass $name, @classes Get classes for invalid input. Return empty string if no error. # Form example # Return next code for invalid I: # You can set additional I<@classes> to set if field invalid. =head2 vvalue $name, $default Get raw input value after validation. Return I<$default> value or empty string before validation. # Form example: # Return next code if user just open form without submit and validation: # # Then user submit form and you validate id. For example user submit "abc": # =head2 vtype $name, %opts Set new type $name if defined %opts. Else return type $name definition. # Get type $self->vtype('mytype'); # Set type # load - requires modules # pre - get int # valid - check for not empty # post - force number $self->vtype('mytype', pre => sub { my ($self, $param) = @_; return int $param // ''; }, valid => sub { my ($self, $param) = @_; return length $param ? 0 : 'Invalid' }, post => sub { my ($self, $param) = @_; return 0 + $param; } ); =head2 vfilter $name, &sub Set new filter $name if defined %opts. Else return filter $name definition. # Get filter $self->vfilter('myfilter'); # Set filter $self->vfilter('myfilter', sub { my ($self, $param, $expression) = @_; return $param eq $expression ? 0 : 'Invalid'; }); Filter sub must return 0 if parameter value is valid. Or error string if not. =head1 SIMPLE SYNTAX You can use the simplified syntax instead of specifying the type, simply by using an expression instead. =over =item I Apply as L filter. No type verification, just match. $self->vparam(myparam => qr{^(abc|cde)$}); =item I $mojo, $value Apply as L function. You need manual verify and set error. $self->vparam(myparam => sub { $_[1] && $_[1] eq 'good' ? 1 : 0 }); =item I Apply as L filter. No type verification, just match. $self->vparam(myparam => [qw(abc cde)]); =back =head1 CONFIGURATION =over =item class CSS class for invalid parameters. Default: field-with-error. =item types You can simple add you own types. Just set this parameters as HashRef with new types definition. =item filters You can simple add you own filters. Just set this parameters as HashRef with new filters definition. =item vsort_page Parameter name for current page number in I. Default: page. =item vsort_rws Parameter name for current page rows count in I. Default: rws. =item rows Default rows count for I. Default: 25. =item vsort_oby Parameter name for current order by I. Default: oby. =item vsort_ods Parameter name for current order destination I. Default: ods. =item ods Default order destination for I. Default: ASC. =item phone_country Phone country. Default: empty. =item phone_region Phone region. Default: empty. =item phone_fix Name of algorithm to fix phone, typicallty country code. Default: empty. =item date Date format for strftime. Default: %F. if no format specified, return L object. =item time Time format for strftime. Default: %T. if no format specified, return L object. =item datetime Datetime format for strftime. Default: '%F %T %z'. if no format specified, return L object. =item blessed By default return objects used for parse or validation: L, L, etc. =item optional By default all parameters are required. You can change this by set this parameter as true. =item address_secret Secret for address:points signing. Format: "ADDRESS:LATITUDE,LONGITUDE[MD5]". MD5 ensures that the coordinates belong to address. =item password_min Minimum password length. Default: 8. =item hash_delimiter Delimiter to split input parameter on two parts: key and value. Default: => - like a perl hash. =item mojo_validator Enable L integration. =back =head1 TYPES List of supported types: =head2 int Signed integer. Use L filter for unsigned. =head2 numeric or number Signed number. Use L filter for unsigned. =head2 money Get money. Use L filter for unsigned. =head2 percent Unsigned number: 0 <= percent <= 100. =head2 str Trimmed text. Must be non empty if required. =head2 text Any text. No errors. =head2 password String with minimum length from I. Must content characters and digits. =head2 uuid Standart 32 length UUID. Return in lower case. =head2 date Get date. Parsed from many formats. See I configuration parameter for result format. See L and even more. =head2 time Get time. Parsed from many formats. See I