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

NAME

Validator::Custom - HTML form validation. Simple and good flexibility

DESCRIPTION

Validator::Custom is a validator for HTML form.

  • 1. Checking functions: ascii_graphic, int, number, in. You can also add your checking function.

  • 2. Filtering functions: trim, remove_blank. You can also add your filtering function.

  • 3. Validation object: Save each validation result and check if all data is valid.

SYNOPSIS

  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 if id is integer
  if (!$vc->check($id, 'int')) {
    # Add failed message
    $validation->add_failed(id => 'id must be integer');
  }
  
  # Check if name has length
  if (!(length $name)) {
    $validation->add_failed(name => 'name must have length');
  }
  # Check if name's length is less than 30
  elsif (!(length $name < 30)) {
    $validation->add_failed(name => 'name is too long');
  }
  
  # Filter price to remove left-rigth space
  $price = $vc->filter($price, 'trim');

  # Check price is number and the digits of the decimal part is two or less than two
  if (!$vc->check($price, 'number', {decimal_part_max => 2})) {
    # Set default value if validation fail
    $price = 20.25;
  }
  
  # Filter each value of favorite using "trim" filtering function
  $favorite = $vc->filter_each($favorite, 'trim');
  
  # Check if favorite has at least one values
  if (@$favorite == 0) {
    $validation->add_failed(favorite => 'favorite must be selected more than one');
  }
  # Check if favorite is one of the specified values
  elsif (!($vc->check_each($favorite, 'in',  ['001', '002', '003']))) {
    $validation->add_failed(favorite => 'favorite is invalid');
  }
  
  # Check if validation result is valid
  if ($validation->is_valid) {
    # ...
  }
  else {
    
    # Check what parameter fail
    unless ($validation->is_valid('name')) {
      # ...
    }
    
    # Get all failed parameter names
    my $failed = $validation->failed;

    # Get a failed parameter message
    my $name_message = $validation->message('name');
    
    # Get all failed parameter messages
    my $messages = $validation->messages;
    
    # Get all failed parameter names and the messages as hash reference
    my $messages_h = $validation->messages_to_hash;
  }
  

1. Basic usage

1. Create a new Validator::Custom object

At first, create Validator::Custom object using new method.

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

2. Prepare input data for validation

Next, prepare input data.

  my $id = 1;
  my $name = 'Ken Suzuki';
  my $price = ' 19.23 ';
  my $favorite = ['001', '002'];

3. Create a new validation object

Next, create a new validation object using validation method.

  my $validation = $vc->validation;

This is Validator::Custom::Validation object to store failed parameter names and the messages.

4. Validate input data

  # Check if id is integer
  if (!$vc->check($id, 'int')) {
    # Add failed message
    $validation->add_failed(id => 'id must be integer');
  }

You can use int checking function to check the value is integer. int checking function is default one. Any checking function is available through check method.

When the check doesn't succeed, you can add the failed parameter name and the message using add_failed method of Validator::Custom::Validation class.

  # Filter price to remove left-rigth space
  $price = $vc->filter($price, 'trim');

You can use trim filtering function to trim left-rigth spaces.

  # Filter each value of favorite using "trim" filtering function
  $favorite = $vc->filter_each($favorite, 'trim');

You can use filter_each method to filter each value of favorite.

  # Check if favorite has at least one values
  if (@$favorite == 0) {
    $validation->add_failed(favorite => 'favorite must be selected more than one');
  }
  # Check if favorite is one of the specified values
  elsif (!($vc->check_each($favorite, 'in',  ['001', '002', '003']))) {
    $validation->add_failed(favorite => 'favorite is invalid');
  }

You can use check_each method to check each value of favorite.

If you see default checks and filter, see "CHECKING FUNCTIONS" in Validator::Custom and "FILTERING FUNCTIONS" in Validator::Custom.

2. Manipulate validation object

If you check all input data is valid, use is_valid method.

  # Check if validation result is valid
  if ($validation->is_valid) {
    # Success
  }
  else {
    # Failed
  }

If you can check a input data is valid, use is_valid method with parameter name.

  # Check what parameter fail
  unless ($validation->is_valid('name')) {
    # ...
  }

You can get all failed parameter names using failed method.

  # Get all failed parameter names
  my $failed = $validation->failed;

You can get a failed parameter message using message method.

  # Get a failed parameter message
  my $name_message = $validation->message('name');

You can get all failed parameter messages using messages method.

  # Get all failed parameter messages
  my $messages = $validation->messages;

You can get all failed names and the messages as hash reference using messages_to_hash method.

  # Get all failed parameter names and the messages as hash reference
  my $messages_h = $validation->messages_to_hash;

See also Validator::Custom::Validation.

3. Advanced tequnique

1. Add checking function

You can add your own checking function using add_check method if you need.

  $vc->add_check(
    telephone => sub {
      my ($vc, $value, $arg) = @_;
      
      my $is_valid;
      if ($value =~ /^[\d-]+$/) {
        $is_valid = 1;
      }
      return $is_valid;
    }
  );

Checking function receives three arguments, First argument is Validator::Custom object, Second argument is the value for checking, Third argument is the argument of checking function.

Your Checking function must return true or false value.

2. Add filtering function

You can add your filtering function by add_filter method if you need.

  $vc->add_filter(
    to_upper_case => sub {
      my ($vc, $value, $arg) = @_;
      
      my $new_$value = uc $value;
                  
      return $new_value;
    }
  );

Filtering function receives three arguments, First argument is Validator::Custom object, Second argument is the value for filtering. Third argument is the argument of filtering function.

Your filtering function must return the result of filtering.

Checking functions

Validator::Custom have the following default checking functions. You can call any checking function by check method.

int

Check if the value is integer value.

  my $value = 19;
  my $is_valid = $vc->check($value, 'int');

Example of valid values:

  "-10"
  "234"

Example of invalid values:

  "10.11"
  "abc"

If you also need to check the range of value, you can write the following way.

  my $is_valid =  $vc->check($value, 'int') && $value > 0;

number

Check if the value is number. Number means integer or decimal.

  my $is_valid = $vc->check($value, 'number');

Example of valid values:

  '1'
  '123'
  '123.456'
  '-1'
  '-100'
  '-100.789'

Example of invalid values:

  'a';
  '1.a';
  'a.1';

You can also specify decimal part max digits using decimal_part_max option.

  my $is_valid = $vc->check($value, 'number', {decimal_part_max => 3});

Example of valid values:

  '123'
  '123.456'
  '-100.789'

Example of invalid values:

  '123.4567'
  '-100.7891'

ascii_graphic

Check if the value is Ascii graphic characters(hex 21-7e). Generally, ascii_graphic function is used to check the characters of a password.

  my $is_valid = $vc->check($value, 'ascii');

Example of valid values:

  "Ken!@-"

Example of invalid values:

  "aa aa"
  "\taaa"

in

Check if the value is one of the given values.

  my $value = '001';
  my $is_valid = $vc->check($value, 'in', ['001', '002', '003']);

Example of valid values:

  '001'
  '002'
  '003'

Example of invalid values:

  '004'
  '005'

Filtering functions

Validator::Custom have the following default filtering functions. You can call any filtering function using filter method.

trim

Trim leading and trailing white space. Note that trim function remove unicode space character, not only [ \t\n\r\f].

  my $new_value = $vc->filter($value, 'trim');

Filtering example:

  Input : '   Ken  '
  Output: 'Ken'

remove_blank

Remove blank character and undefined value from array reference.

  my $new_values = $vc->filter($values, 'remove_blank');

Filtering example:

  Input : [1, 2, '', undef, 4]
  Output: [1, 2, 4]

Methods

Validator::Custom inherits all methods from Object::Simple and implements the following new ones.

new

Create a new Validator::Custom object.

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

add_check

Add a checking function.

  $vc->add_check(int => sub { ... });

Example:

  $vc->add_check(
    int => sub {
      my ($vc, $value, $arg) = @_;
      
      my $is_valid = $value =~ /^\-?[\d]+$/;
      
      return $is_valid;
    }
  );

Checking function receives three arguments, First argument is Validator::Custom object, Second argument is the value for checking, Third argument is the argument of checking function.

Your Checking function must return true or false value.

add_filter

Add a filtering function.

  $vc->add_filter(trim => sub { ... });

Example:

  $vc->add_filter(
    trim => sub {
      my ($vc, $value, $arg) = @_;
      
      $value =~ s/^\s+//;
      $value =~ s/\s+$//;
      
      return $value;
    }
  );

check

Execute a checking function.

  my $is_valid = $vc->check($value, 'int');
  my $is_valid = $vc->check($value, 'int', $arg);

First argument is the value for checking. Second argument is the name of the checking funcion. Third argument is the argument of the checking function.

check_each

Execute a checking function to all elements of array reference. If more than one element is invalid, check_each method return false.

  my $is_valid = $vc->check_each($values, 'int');
  my $is_valid = $vc->check_each($values, 'int', $arg);

First argument is the values for checking, which must be array reference. Second argument is the name of the checking funcion. Third argument is the argument of the checking function.

filter

Execute a filtering function.

  my $new_value = $vc->filter($value, 'trim');
  my $new_value = $vc->filter($value, 'trim', $arg);

First argument is the value for filtering. Second argument is the name of the filtering funcion. Third argument is the argument of the filtering function.

filter_each

Execute a filtering function to all elements of array reference.

  my $new_values = $vc->filter_each($values, 'trim');
  my $new_values = $vc->filter_each($values, 'trim', $arg);

First argument is the values for filtering, which must be array reference. Second argument is the name of the filtering funcion. Third argument is the argument of the filtering function.

EXAMPLES

Show you some examples to do some validation.

Password checking:

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

Check box, selected at least 1, one of the given values:

  my $favorite = ['001', '002'];

  my $validation = $vc->validation;
  
  if (@$favorite == 0) {
    $validation->add_failed(favorite => 'favorite must be selected at least 1');
  }
  elsif (!$vc->check($favorite, 'in', ['001', '002', '003'])) {
    $validation->add_failed(favorite => 'favorite have invalid value');
  }
  
  if ($validtion->is_valid) {
    # ...
  }
  else {
    # ...
  }

Convert date string to Time::Piece object.

  my $date = '2014/05/16';
  
  my $validation = $vc->validation;
  
  my $date_tp;
  if (!length $date) {
    $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');
    }
  }

FAQ

I use Validator::Custom 0.xx yet. I want to see documentation of Version 0.xx.

See Validator::Custom::Document::Version0. This is complete document for Validator::Custom version 0.xx.

What point I take care of in Version 1.xx.

  • in_array constraint function is renamed to in checking function.

  • trim filtering function becomes triming unicode space characters, not only [ \t\n\r\f].

  • decimal constraint is renamed to number checking function and simplified.

  • date_to_timepiece checking function doesn't exist. About alternative way, see the topic "Convert date string to Time::Piece object" in "EXAMPLES".

  • datetime_to_timepiece checking function doesn't exists. About alternative way, see the topic "Convert datetime string to Time::Piece object" in "EXAMPLES".

How to create the corresponding checking functions in Version 0.xx constraint functions.

I show 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 to create the corresponding filtering functions in Version 0.xx constraint functions.

I show 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 at gmail.com>

http://github.com/yuki-kimoto/Validator-Custom

COPYRIGHT & LICENCE

Copyright 2009-2017 Yuki Kimoto, all rights reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.