Validator::Custom - validation of HTML input data
Validator::Custom is a Perl module to help validate HTML forms. You can concisely describe value checking and filtering, and error message handling. It is extremely easy to use and can flexibly handle complex validation combinations.
Name
Validator::Custom - HTML form validation, concise and flexible
How to use
use Validator::Custom; my $vc = Validator::Custom->new; # Input data my $id = 1; my $name = 'Ken Suzuki'; my $price = '19.23'; my $favorite = ['001', '002']; # Create validation object my $validation = $vc->validation; # Check that "ID" is an integer if (!$vc->check($id, 'int')) { # Add message on failure $validation->add_failed(id =>'id must be integer'); } # Check that the "name" has a length if (! (length $name)) { $validation->add_failed(name =>'name must have length'); } # Check that the length of the "name" is less than 30 elsif (! (length $name < 30)) { $validation->add_failed(name =>'name is too long'); } # Filter "price" to remove left and right blanks $price = $vc->filter($price, 'trim'); # Check that "Price" is a number with two decimal places if (!$vc->check($price ,, 'number', {decimal_part_max => 2})) { # Set default value if validation fail $price = 20.25; } # Filter each value of "Favorites" using the "trim" filter function $favorite = $vc->filter_each($favorite, 'trim'); # Check that "Favorites" have at least one value if (@$favorite == 0) { $validation->add_failed(favorite =>'favorite must be selected more than one'); } # Check that "Favorites" is one of "001", "002", and "003" elsif (! ($vc->check_each($favorite, 'in', ['001', '002', '003']))) { $validation->add_failed(favorite =>'favorite is invalid'); } # Check if the validation result is correct if ($validation->is_valid) { # ... } else { # Check which parameter failed unless ($validation->is_valid('name')) { # ... } # Get the names of all failed parameters my $failed = $validation->failed; # Get message for one failed parameter my $name_message = $validation->message('name'); # Get messages for all failed parameters my $messages = $validation->messages; # Get the names and messages of all failed parameters as a hash reference my $messages_h = $validation->messages_to_hash; }
=====
Explanation
Validator::Custom is a validator of HTML forms, with simplicity and good flexibility.
The features are as follows.
- Some check functions are available by default. ascii_graphic , int , number , in , etc.
- Some filter functions are available by default. trim , remove_blank , etc.
- You can add its own check and filter functions.
- A concise validation object is available. You can save the names and messages of failed parameters in order.
Guide
1. Basics
1. Create a new Validator::Custom object
First, use the new method to create a Validator::Custom object.
use Validator::Custom; my $vc = Validator::Custom->new;
2. Preparation of input data for validation
Next, prepare the input data.
my $id = 1; my $name = 'Ken Suzuki'; my $price = '19.23'; my $favorite = ['001', '002'];
3. Creating a validation object
Then use the validation method to create a new validation object.
my $validation = $vc->validation;
this is,
Validator::Custom::Validation object to store the failed parameter name and message.
4. Validation of input data
# Check that "ID" is an integer if (!$vc->check($id, 'int')) { # Add message on failure $validation->add_failed(id =>'id must be integer'); }
You can use the int check function to check that the value is an integer. The int check function is the default check function. The check function is available through the check method.
If the check is unsuccessful, give the name and message of the failing parameter to the add_failed of Validator::Custom::Validation class. You can add it using the b> method.
# Filter "price" to remove left and right blanks $price = $vc->filter($price, 'trim');
You can use the trim filter function to remove the left and right spaces.
# Filter each value of "Favorites" using the "trim" filter function $favorite = $vc->filter_each($favorite, 'trim');
You can use the filter_each method to filter each value of "Favorites".
# Check that "Favorites" have at least one value if (@$favorite == 0) { $validation->add_failed(favorite =>'favorite must be selected more than one'); } # Check that "Favorites" is one of "001", "002", and "003" elsif (! ($vc->check_each($favorite, 'in', ['001', '002', '003']))) { $validation->add_failed(favorite =>'favorite is invalid'); }
You can use the check_each method to check each value of "favorites".
If you want to know the default check function and filter function, see the "Check function" and "Filter function" items.
2 Handling of validation objects
Use the is_valid method to check that all input data is correct.
# Make sure the validation results are correct if($validation->is_valid) { # Success } else { # Failure }
If you want to check if one input data is correct, use the is_valid method with parameters.
# Check which parameter failed unless ($validation->is_valid('name')) { # ... }
You can use the failed method to get the names of all parameters that failed validation.
# Get the names of all parameters that failed validation my $failed = $validation->failed;
You can use the message method to get the message of the parameter that failed validation.
# Get message for parameters that failed validation my $name_message = $validation->message('name');
You can use the messages method to get messages for all parameters that failed validation.
# Get messages for all parameters that failed validation my $messages = $validation->messages;
You can use the messages_to_hash method to get the names and messages of all parameters that failed validation in hash-reference format.
# Get the names and messages of all failed parameters as a hash reference my $messages_h = $validation->messages_to_hash;
Please also refer to Validator::Custom::Validation.
3 Advanced technology
1. Addition of check function
If you want, you can add the check function yourself using the add_check method.
$vc->add_check( telephone => sub { my ($vc, $value, $arg) = @_; my $is_valid; if ($value =~ /^[\d-]+$/) { $is_valid = 1; } return $is_valid; } );
The check function takes three arguments. The first argument is the Validator::Custom object, the second argument is the value to check, and the third argument is the argument to the check function.
The check function must return a true or false value.
2. Addition of filter function
If you want, you can add the filter function yourself using the add_filter method.
$vc->add_filter( to_upper_case => sub { my ($vc, $value, $arg) = @_; my $new_ $value = uc $value; return $new_value; } );
The filter function takes three arguments. The first argument is the Validator::Custom object, the second argument is the value for filtering, and the third argument is the argument to the filter function.
The filter function should return the result of the filter.
Check function
Validator::Custom has the following default check functions: All check functions can be called using the check method.
int
my $value = 19; my $is_valid = $vc->check($value, 'int');
Check if it is an integer value.
Example of correct value
"-Ten" "234"
Illegal value example
"10.11" "abc"
If you also want to check the range of values, you can write:
my $is_valid = $vc->check($value, 'int') && $value > 0;
number
my $is_valid = $vc->check($value, 'number');
Checks if the value is a number. Numbers mean integers and decimals.
Example of correct value:
'1' 'one two Three' '123.456' '-1' '-100' '-100.789'
Illegal value example:
'a'; '1.a'; 'a.1';
You can also use the decimal_part_max option to specify the maximum number of decimal places.
my $is_valid = $vc->check($value, 'number', {decimal_part_max => 3});
Example of correct value:
'one two Three' '123.456' '-100.789'
Illegal value example:
'12 3.4567' '-100.7891'
ascii_graphic
my $is_valid = $vc->check($value, 'ascii');
Check if the value is an ASCII graphic character (hexadecimal "21-7e"). Generally, it is used to check the characters of the password.
Example of correct value:
"Ken! @-"
Illegal value example:
"aa aa" "\taaa"
in
my $value = '001'; my $is_valid = $vc->check($value, 'in', ['001', '002', '003']);
Checks if the value is one of several given values.
Example of correct value:
'001' '002' '003'
Illegal value example:
'004' '005'
Filter function
Validator::Custom has the following default filter functions: All filter functions are y C
trim
my $new_value = $vc->filter($value, 'trim');
Remove the leading and trailing blanks. Note that it removes Unicode whitespace as well as ASCII whitespace [\t\n\r\f].
Filtering example:
Input:'Ken' Output:'Ken'
remove_blank
my $new_values = $vc->filter($values, 'remove_blank');
Removes empty and undefined characters from the array reference.
Filtering example:
Input: [1, 2, '', undef, 4] Output: [1, 2, 4]
Method
Validator::Custom inherits all the methods of Object::Simple And implements the following new methods:
new
my $vc = Validator::Custom->new;
Create a new Validator::Custom object.
add_check
$vc->add_check(int => sub {...});
Add a check function.
example:
$vc->add_check( int => sub { my ($vc, $value, $arg) = @_; my $is_valid = $value =~ /^\-? [\D]+$/; return $is_valid; } );
The check function takes three arguments. The first argument is the Validator::Custom object, the second argument is the value to check, and the third argument is the argument to the check function. The check function must return a true or false value.
add_filter
$vc->add_filter(trim => sub {...});
Add a filter function.
example:
$vc->add_filter( trim => sub { my ($vc, $value, $arg) = @_; $value =~ s/^\s+//; $value =~ s/\s+$//; return $value; } );
The filter function takes three arguments. The first argument is the Validator::Custom object, the second argument is the value for filtering, and the third argument is the argument to the filter function.
The filter function should return the result of the filter.
check
my $is_valid = $vc->check($value, 'int'); my $is_valid = $vc->check($value, 'int', $arg);
Execute the check function.
The first argument is the value to check. The second argument is the name of the check function. The third argument is the argument of the check function.
check_each
my $is_valid = $vc->check_each($values, 'int'); my $is_valid = $vc->check_each($values, 'int', $arg);
Executes the check function on all elements of the array reference. If one or more values are invalid, the check_each method returns a fake value.
The first argument is the value to check. This should be an array reference. The second argument is the name of the check function. The third argument is the argument of the check function.
filter
my $new_value = $vc->filter($value, 'trim'); my $new_value = $vc->filter($value, 'trim', $arg);
Execute the filter function.
The first argument is the value to filter. The second argument is the name of the filter function. The third argument is the argument of the filter function.
filter_each
my $new_values = $vc->filter_each($values, 'trim'); my $new_values = $vc->filter_each($values, 'trim', $arg);
Executes the filter function on all elements of the array reference.
The first argument is the value to filter. This should be an array reference. The second argument is the name of the filter function. The third argument is the argument of the filter function.
Example
Here are some examples for validation.
Password check:
my $password = 'abc'; my $password2 = 'abc'; my $validation = $vc->validation; if (! length $password) { $validation->add_failed(password =>'password must have length'); } elsif (!$vc->check($password, 'ascii')) { $validation->add_failed(password =>'password contains invalid characters'); } elsif ($password ne $password2) { $validation->add_failed(password => "two passwords don't match"); } if ($validation->is_valid) { # ... } else { # ... }
At least one check box is selected. Specific value.
my $favorite = ['001', '002']; my $validation = $vc->validation; if (@$favorite == 0) { $validation->add_failed(favorite =>'favorite must be selected at least 1'); } elsif (!$V c->check($favorite, 'in', ['001', '002', '003'])) { $validation->add_failed(favorite =>'favorite have invalid value'); } if ($validation->is_valid) { # ... } else { # ... }
Convert date string to Time::Piece object:
my $date = '2014/05/16'; my $validation = $vc->validation; my $date_tp; if (! length $datetime) { $validation->add_failed(date =>'date must have length'); } else { eval {$date_tp = Time::Piece->strptime($date, '%Y /%m /%d')}; if (!$date_tp) { $validation->add_failed(date =>'date value is invalid'); } }
Convert datetime string to Time::Piece object:
my $datetime = '2014/05/16 12:30:40'; my $validation = $vc->validation; my $datetime_tp; if (! length $datetime) { $validation->add_failed(datetime =>'datetime must have length'); } else { eval {$datetime_tp = Time::Piece->strptime($datetime, '%Y /%m /%d%H:%M:%S')}; if (!$Datetime_tp) { $validation->add_failed(datetime =>'datetime value is invalid'); } }
(Reference) eval
FAQ
I'm still using the 0.xx version of Validator::Custom. I would like to see the documentation.
Validator::Custom::Document::Version0 please look. This is the complete documentation for "Validator::Custom 0.xx".
What should I be aware of in version 1.xx?
- The in_array constraint function has been renamed to the in check function.
- The trim filter function now removes unicode strings as well as [\t\n\r\f].
- The decimal constraint function has been renamed to the number check function for simplification.
- The date_to_timepiece constraint function no longer exists. For an alternative method, see "Converting a Date String to a Time::Piece Object" in the Examples.
- The datetime_to_timepiece constraint function no longer exists. For an alternative method, see "Converting Date-Time Strings to Time::Piece Objects" in the Examples.
How do I create a check function that corresponds to a version 0.xx constraint function?
I will show you some examples.
space
$vc->add_check(space => sub { my ($vc, $value, $arg) = @_; return defined $value && $value =~ '^[\t\n\r\f] * $'? 1: 0; });
http_url
$vc->add_check(http_url => sub { my ($vc, $value, $arg) = @_; return defined $value && $value =~ /^s? https ?: \/\/[-_.!~ *'() A-zA-Z0-9;\/?: \@& = + \$, % # ]+$/? 1: 0; });
decimal
$vc->add_check(decimal => sub { my ($vc, $value, $arg) = @_; return undef unless defined $value; my $digits_tmp = $arg; # Digit my $digits; if (defined $digits_tmp) { if (ref $digits_tmp eq 'ARRAY') { $digits = $digits_tmp; } else { $digits = [$digits_tmp, undef]; } } else { $digits = [undef, undef]; } # Regex my $re; if (defined $digits->[0] && defined $digits->[1]) { $re = qr/^[0-9]{1, $digits->[0]} (\. [0-9]{0, $digits->[1]})? $/; } elsif (defined $digits->[0]) { $re = qr/^[0-9]{1, $digits->[0]} (\. [0-9] *)? $/; } elsif (defined $digits->[1]) { $re = qr/^[0-9]+(\. [0-9]{0, $digits->[1]})? $/; } else { $re = qr/^[0-9]+(\. [0-9] *)? $/; } # Check value if ($value =~ /$re/) { return 1; } else { return 0; } }
How do I create a filter function that corresponds to the version 0.xx constraint function?
I will show you some examples.
trim_collapse
$vc->add_filter(trim_collapse => sub { my ($vc, $value, $arg) = @_; return undef unless defined $value; $value =~ s/[\t\n\r\f]+// g; $value =~ s/^[\t\n\r\f] * (. *?) [\t\n\r\f] *$/ $1/ms; return $value; });
trim_lead
$vc->add_filter(trim_lead => sub { my ($vc, $value, $arg) = @_; return undef unless defined $value; $value =~ s/^[\t\n\r\f]+(. *)$/ $1/ms; return $value; });
trim_trail
$vc->add_filter(trim_trail => sub { my ($vc, $value, $arg) = @_; return undef unless defined $value; $value =~ s/^(. *?) [\t\n\r\f]+$/ $1/ms; return $value; });
trim_uni
$vc->add_filter(trim_uni => sub { my ($vc, $value, $arg) = @_; return undef unless defined $value; $value =~ s/^\s * (. *?)\S *$/ $1/ms; return $value; });
trim_uni_collapse
$vc->add_filter(trim_uni_collapse => sub { my ($vc, $value, $arg) = @_; return undef unless defined $value; $value =~ s/\s+// g; $value =~ s/^\s * (. *?)\S *$/ $1/ms; return $value; });
trim_uni_lead
$vc->add_filter(trim_uni_lead => sub { my ($vc, $value, $arg) = @_; return undef unless defined $value; $value =~ s/^\s+(. *)$/ $1/ms; return $value; });
trim_uni_trail
$vc->add_filter(trim_uni_trail => sub { my ($vc, $value, $arg) = @_; return undef unless defined $value; $value =~ s/^(. *?)\S+$/ $1/ms; return $value; });
Author
Yuki Kimoto (kimoto.yuki@gmail.com)
[http://github.com/yuki-kimoto/Validator-Custom]
Validator::Custom check function example
Here are some example check functions such as "Hiragana", "Katakana", and email address check.
Documentation for Validator::Custom 1.0 and earlier
Documentation for Validator::Custom 1.0 and earlier can be found here.
Check function example
Here are some example check functions for validation in Validator::Custom.
Hiragana and Katakana
To determine that it is Hiragana and Katakana , register the following constraint function.
# Hiragana $vc->add_check( hiragana => sub { my ($vc, $value) = @_; my $is_valid = $value =~ /^\p{InHiragana}+$/; return $is_valid; } ); # Katakana $vc->add_check( katakana => sub { my ($vc, $value) = @_; my $is_valid = $value =~ /^\p{InKatakana}+$/ return $is_valid; } );
Email validation
Email validation is not provided as a default check function. If necessary, it is recommended to install Email::Valid::Loose and then register and use the check function.
use Email::Valid::Loose; $vc->add_check( email => sub { my ($vc, $value) = @_; return Email::Valid::Loose->address($value); } );